UITextField:文本输入框
//初始化
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(30, 30, 150, 30)];
//边框类型 若不设置此属性 则无边框
textField.borderStyle = UITextBorderStyleRoundedRect;
//占位符,未输入信息时候显示的内容
textField.placeholder = @"请输入信息";
//设置text显示信息
textField.text = @"呵呵";
//设置文字的颜色
textField.textColor = [UIColor redColor];
//设置文字的字体样式
textField.font = [UIFont systemFontOfSize:16];
//设置文字的对齐方式 (左对齐)
textField.textAlignment = NSTextAlignmentLeft;
[self.view addSubview:textField];
设置键盘
//设置输入框是否可用 默认YES
textField.enabled = YES;
//设置弹出的键盘类型
textField.keyboardType = UIKeyboardTypeDefault;
//设置returnKey按钮的样式
textField.returnKeyType = UIReturnKeySend;
//当开始输入内容的时候清除掉之前的所有内容
textField.clearsOnBeginEditing = YES;
//设置文字为安全样式 "*****"样式
textField.secureTextEntry = YES;
自定义 输入控件 (系统默认弹出键盘,此属性设置后弹出自定义控件)。可以在View上加任意控件,自定义键盘,手写键盘等
//在UI开发中只要参数要求是UIView类型的,那么就标志着可以传任意类型的控件
UIView *aView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 50)];
aView.backgroundColor = [UIColor orangeColor];
//添加辅助视图,贴在输入板上面的View
textField.inputAccessoryView = aView;
//自定义一个输入板
UIView *wView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 200)];
wView.backgroundColor = [UIColor greenColor];
textField.inputView = wView;
设置textField中的左视图、右视图、删除按钮
//设置边框样式
textField.borderStyle = UITextBorderStyleRoundedRect;
//设置清除按钮的样式
textField.clearButtonMode = UITextFieldViewModeAlways;
//这个是两个一起配套使用的,先设置mode,在设置leftView
textField.leftViewMode = UITextFieldViewModeAlways;
UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
leftView.backgroundColor = [UIColor redColor];
textField.leftView = leftView;
//有左视图,必然有右视图,设置右视图后会覆盖掉clearButtonMode
//注意:左右视图会挤占TextField的使用空间,在使用左右视图的时候,一定要计算好大小
textField.rightViewMode = UITextFieldViewModeAlways;
UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 30)];
rightView.backgroundColor = [UIColor greenColor];
textField.rightView = rightView;
还有两个方法经常用到:
//注销第一响应者,键盘回收
[textField resignFirstResponder];
//称为第一响应者,键盘弹出
[textField becomeFirstResponder];
UITextField 若要实现代理方法,必须遵守 UITextFieldDelegate。只有下列几个方法,直接翻译过来就是方法名含义,就不一一列举何时被调用了。
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;
- (void)textFieldDidBeginEditing:(UITextField *)textField;
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField;
- (void)textFieldDidEndEditing:(UITextField *)textField;
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
- (BOOL)textFieldShouldClear:(UITextField *)textField;
- (BOOL)textFieldShouldReturn:(UITextField *)textField;