UITextField *userNameTextField = [[UITextField alloc] init]; userNameTextField.frame = CGRectMake(30, 100, 220, 50); [self.window addSubview:userNameTextField]; [userNameTextField release]; // 設置樣式 userNameTextField.borderStyle = UITextBorderStyleRoundedRect; userNameTextField.placeholder = @"Enter your name"; userNameTextField.text = @"OUTLAN"; userNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing; // 右側刪除按鈕出現時機 // 左側裝飾 view UILabel *leftLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 20, 20)]; leftLable.text = @"N"; userNameTextField.leftView = leftLable; userNameTextField.leftViewMode = UITextFieldViewModeAlways; [leftLable release]; userNameTextField.enabled = YES; // 是否允許輸入 userNameTextField.clearsOnBeginEditing = NO; // 編輯時是否清空 userNameTextField.secureTextEntry = NO; // 是否以圓點呈現(密碼) userNameTextField.keyboardAppearance = UIKeyboardAppearanceDark; // 鍵盤顏色 userNameTextField.keyboardType = UIKeyboardTypeEmailAddress; // 鍵盤樣式 userNameTextField.returnKeyType = UIReturnKeySearch; // return 鍵樣式 // 替換鍵盤(自訂 inputView) UIView *keyBoard = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 300)]; keyBoard.backgroundColor = [UIColor greenColor]; // userNameTextField.inputView = keyBoard; [keyBoard release]; // 鍵盤上方的輔助條(inputAccessoryView) UIView *inputAccessView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 20)]; inputAccessView.backgroundColor = [UIColor yellowColor]; userNameTextField.inputAccessoryView = inputAccessView; [inputAccessView release];
第一步,設置代理對象,通常為 self:
textField.delegate = self;
第二步,當前類遵守協議:
@interface AppDelegate : UIResponder@end
第三步,實現協議方法:
// 點擊 return 時收回鍵盤
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
NSLog(@"點擊了 Return");
[textField resignFirstResponder]; // 放棄第一響應者,收回鍵盤
return YES;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
NSLog(@"beginning");
return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
NSLog(@"ending");
return YES;
}
收回鍵盤的核心就是讓 textField 呼叫 resignFirstResponder 放棄第一響應者身份。透過 textFieldShouldReturn: 代理方法,就能在使用者按下鍵盤 return 鍵時優雅地收起鍵盤。