几个UITextField,需要在键盘和UIDatePicker之间切换

时间:2010-12-05 12:32:46

标签: iphone objective-c keyboard uitextfield uidatepicker

在我的视图中我有几个UITextFields,我需要显示一些文本输入的键盘,有时需要显示UIDatePicker。

我命令显示DatePicker我为日期UITextField实现了委托,但是一旦我为文本输入选择了另一个UITextField,DatePicker仍然在后台。然后我尝试使用此代码实现另一个UITextField的委托:

- (void)viewDidLoad {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd/MM/yyyy"];
NSString *stringFromDate = [formatter stringFromDate:[NSDate date]];
NSLog(@"IN - AddExpenseViewController::viewDidLoad %s",stringFromDate);
date.text = stringFromDate;

datePicker.hidden = YES;
date.delegate = self;

amount.delegate = self;

isIncome = NO;


[super viewDidLoad]; }

// ...

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
NSLog(@"IN - AddExpenseViewController::textFieldShouldBeginEditing %@",textField.placeholder);
if (![textField.placeholder isEqual:[NSString stringWithFormat:@"Date"]]) {
    [self hideDatePicker];
    [textField becomeFirstResponder];
    return YES;
}
else {
    [self showDatePicker];
}
return NO;}

问题是,当我选择日期TextField而不是金额时,委托会在循环中被调用:

2010-12-05 13:15:17.324 AddExpense [1179:207] IN - AddExpenseViewController :: textFieldShouldBeginEditing Amount 2010-12-05 13:15:17.324 AddExpense [1179:207] IN - AddExpenseViewController :: hideDatePicker 2010-12-05 13:15:17.325 AddExpense [1179:207] IN - AddExpenseViewController :: textFieldShouldBeginEditing Amount 2010-12-05 13:15:17.326 AddExpense [1179:207] IN - AddExpenseViewController :: hideDatePicker 2010-12-05 13:15:17.327 AddExpense [1179:207] IN - AddExpenseViewController :: textFieldShouldBeginEditing Amount 2010-12-05 13:15:17.327 AddExpense [1179:207] IN - AddExpenseViewController :: hideDatePicker

并且没有办法阻止它! 我的代码出了什么问题?

提前致谢,AM

1 个答案:

答案 0 :(得分:1)

每当您创建UITextField firstReponder时,textFieldShouldBeginEditing:都会发送给其委托。 临时解决方案可能是

if (![textField.placeholder isEqual:[NSString stringWithFormat:@"Date"]]) {
    [self hideDatePicker];
    textField.delegate = nil;
    [textField becomeFirstResponder];
    textField.delegate = self;
    return YES;
}

但我建议您重新设计代码,以便从该方法中排除[textField becomeFirstResponder]