将UITextField格式化为时间hh:mm

时间:2012-01-19 09:37:57

标签: objective-c uitextfield

我希望UITextField能够正确地将输入的数字格式化为时间,使用“shouldChangeCharactersInRange”添加分钟以在每次按下新数字时获得此结果:

i.e.: 
00:00
00:08 = 8 pressed
01:23 = 8 -> 3 pressed
08:30 = 8 -> 3 -> 0 pressed

UITextField是Custom UITableViewCell的子视图。 我不知道,提前谢谢。

2 个答案:

答案 0 :(得分:0)

简单

在H声明中:

@interface ViewController : UIViewController
{
    int hh;
    int mm;
    int ss;
}


@property (strong, nonatomic) IBOutlet UILabel *outputLabel;

@end

在M

-(void)generateText
{
    NSString *hhString;
    NSString *mmString;
    NSString *ssString;

    if (hh < 10){
        hhString = [NSString stringWithFormat:@"0%d",hh];
    } else {
        hhString = [NSString stringWithFormat:@"%d",hh];
    }
    //
    if (mm < 10){
        mmString = [NSString stringWithFormat:@"0%d",mm];
    } else {
        mmString = [NSString stringWithFormat:@"%d",mm];
    }
    if (ss < 10){
        ssString = [NSString stringWithFormat:@"0%d",ss];
    } else {
        ssString = [NSString stringWithFormat:@"%d",ss];
    }





    NSString *outputText = [NSString stringWithFormat:@"%@:%@:%@",hhString,mmString,ssString];
    NSLog(@"output string = %@",outputText);
    outputLabel.text = outputText;

}


-(IBAction)addHH:(id)sender
{
    hh = hh +1;
    [self generateText];
}

-(IBAction)addMM:(id)sender
{
    mm = mm +1;
    [self generateText];
}

-(IBAction)addSS:(id)sender
{
    ss = ss +1;
    [self generateText];
}

在“界面”构建器中,使用3个按钮激活相应的IBAction

答案 1 :(得分:0)

http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html

使用此委托方法相应地更改文本字段

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // You should already have set some string in the text field
    if (/*user input is between 0-9*/) {
        NSString *text = /* Format your text */
        textFiled.text = text;
        // Return NO to disable editing done by the user
        // Not required to return here if you always return NO;
        return NO;
    }
    // Return NO if you do not want to let user make any changes, otherwise YES
    return YES;
}

我已对其进行了测试,但更改此方法中的textField.text可能会以递归方式调用此方法并失败。如果是这种情况,请使用标记来跟踪您所做的更改以及用户的更改。如果标志为ON则返回YES,否则返回NO

相关问题