我試圖把一個UIButton放在UITextfield中,充當「完成」按鈕來辭去響應者。我已經嘗試了以下代碼,當字段開始編輯UITextField中的done按鈕時,leftView是可見的,但是如果我從datePicker中選擇一個值或使用鍵盤(在模擬器中)進行任何文本輸入,done按鈕消失並顯示右側的clearButton。UITextField內的UIButton
現在看來似乎他們兩人之間進行切換,我改變textFld.LeftViewMode,始終顯示按鈕,但不是想我......
在此先感謝!
- (void)viewDidLoad
{
[super viewDidLoad];
txtFld = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 310, 25)];
txtFld.placeholder = @"__/__/____";
txtFld.font = [UIFont fontWithName:@"HelveticaNeue" size:11];
txtFld.textAlignment = NSTextAlignmentCenter;
txtFld.contentVerticalAlignment = UIControlContentHorizontalAlignmentCenter;
txtFld.contentHorizontalAlignment = UIControlContentVerticalAlignmentCenter;
txtFld.clearButtonMode = UITextFieldViewModeWhileEditing;
txtFld.borderStyle = UITextBorderStyleRoundedRect;
UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
doneButton.bounds = CGRectMake(0, 0, 40, 20);
doneButton.frame = CGRectMake(0.0, 0.0, 40.0, 20.0);
doneButton.titleLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:10];
[doneButton setTitle:@"Done" forState:UIControlStateNormal];
doneButton.imageEdgeInsets = UIEdgeInsetsMake(0, -16, 0, 0);
[doneButton addTarget:self action:@selector(resignResponder:) forControlEvents:UIControlEventTouchUpInside];
doneButton.userInteractionEnabled = YES;
// Add button to the UITextField
txtFld.leftView = doneButton;
txtFld.leftViewMode = UITextFieldViewModeWhileEditing;
UIDatePicker *datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker addTarget:self action:@selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
[txtFld setInputView:datePicker];
[self.view addSubview:txtFld];
}
-(void)resignResponder:(UIButton *)sender{
UITextField *associatedTxtFld = (UITextField *) sender.superview ;
if ([associatedTxtFld isFirstResponder]) {
[associatedTxtFld resignFirstResponder];
}
}
-(void)datePickerValueChanged:(id)sender{
UIDatePicker *picker = (UIDatePicker *)sender;
NSDateFormatter *formater = [[NSDateFormatter alloc]init];
[formater setDateFormat:@"dd-MM-yyyy"];
txtFld.text = [formater stringFromDate:picker.date];
}
你最好添加一個工具欄作爲文本字段的inputAccessoryView。將完成按鈕(以及可能的下一個和上一個按鈕)添加到工具欄。這是一種更常見的方法。 – rmaddy 2013-03-18 20:01:40