ios UITextField
加入TextFieldDelagate
@interface RootViewController () <UITextFieldDelegate>
@property (nonatomic, strong) UITextField *usernameTextField;
@property (nonatomic, strong) UITextField *passwordTextField;
@end
#pragma mark - 创建textField
// 移除view1 view2
[view1 removeFromSuperview];
[view2 removeFromSuperview];
// 1. 初始化
UITextField *usernameTextField =
[[UITextField alloc] initWithFrame:CGRectMake(0, 150, 375, 30)];
// 2. 配置属性
// 2.1 配置边框
usernameTextField.borderStyle = UITextBorderStyleRoundedRect;
// 2.2 配置纠正自动大小写
usernameTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
// 2.3 配置自动纠正功能
usernameTextField.autocorrectionType = UITextAutocorrectionTypeNo;
// 2.4 配置键盘
usernameTextField.keyboardType = UIKeyboardTypeNumberPad;
// 2.5 配置return键
usernameTextField.returnKeyType = UIReturnKeyDone;
// 2.6 配置清除属性
usernameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
// 2.7 leftView
// usernameTextField.leftView = 图片视图
// usernameTextField.leftViewMode = UITextFieldViewModeAlways
// 3. 添加到父视图
[self.view addSubview:usernameTextField];
#pragma mark - 密码文本框
// 1. 初始化
UITextField *passwordTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 200, 375, 30)];
// 2. 配置属性
// 2.1 配置安全输入
passwordTextField.secureTextEntry = YES;
// 2.2 配置边框
passwordTextField.borderStyle = UITextBorderStyleRoundedRect;
// 3. 添加到父视图
[self.view addSubview:passwordTextField];
// 4. 设置委托人
usernameTextField.delegate = self;
passwordTextField.delegate = self;=
// 进行属性关联
self.usernameTextField = usernameTextField;
self.passwordTextField = passwordTextField;
#pragma mark - UITextFieldDelegate methods
// 是否进行返回
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
// 失去焦点
[textField resignFirstResponder];
return YES;
}
// 是否用字符串替换某个范围的字符串
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSLog(@"range = %@, string = %@", NSStringFromRange(range), string);
// 获取文本框中的字符串
NSString *text = textField.text;
// 长度限定
if (text.length + string.length > 10) {
return NO;
}
// 内容限定
// NSPredicate 谓词
return YES;
}