UITextField是一个类,用来接收用户的输入,就是常见的文本输入框,不过一般是输入用户名密码之类的那种输入框。只能一行显示。
UITextView是一个类,也可以用来接收用户的输入,不过与UITextField不同的是,它能接收超过一行的数据,可以换行。
UITextField的部分属性
预备知识:第一响应者
当用户点击一个UITextField、UITextView时表明他要输入数据,点击的这个控件就会成为第一响应者(firstResponder ),系统就会自动弹出键盘。我们可以通过becomeFirstResponder方法来自己定义什么时候该弹出键盘: [self.textfeild becomeFirstResponder] 我们也可以通过 resignFirstResponder 来取消一个控件的的第一响应者:[self.textfiled resignFirstResponder]。
正式开始:
(1) //初始化textfield并设置位置及大小
UITextField *text = [[UITextField alloc]initWithFrame:CGRectMake(20, 20, 130, 30)];
(2) //设置边框样式,只有设置了才会显示边框样式
text.borderStyle = UITextBorderStyleRoundedRect;
typedef enum {
UITextBorderStyleNone,
UITextBorderStyleLine,
UITextBorderStyleBezel,
UITextBorderStyleRoundedRect //圆角矩形
} UITextBorderStyle;
(3) //设置输入框的背景颜色,此时设置为白色 如果使用了自定义的背景图片边框会被忽略掉
text.backgroundColor = [UIColor whiteColor];
如果想要改变输入框边框的颜色,需要用到这个控件的layer属性的bordercolor属性,这是一个CGColor类型,所以需要类型转换
text.layer.borderColor = [UIColor greenColor].CGColor;
(4) //设置背景
注意: 只有在 UITextBorderStyleNone 样式下,设置背景图才会生效,且图片大小小于 text 的frame时,图片会拉伸
text.background = [UIImage imageNamed:@"dd.png"];
(5) //设置背景 设置enable为NO 时的背景图片
text.disabledBackground = [UIImage imageNamed:@"cc.png"];
(6) //当输入框没有内容时,水印提示 提示内容为password
text.placeholder = @"password";
(7) //设置输入框内容的字体样式和大小
text.font = [UIFont fontWithName:@"Arial" size:20.0f];
(8) //设置字体颜色
text.textColor = [UIColor redColor];
(9) //输入框中是否有个叉号,在什么时候显示,用于一次性删除输入框中的内容
text.clearButtonMode = UITextFieldViewModeAlways;
typedef enum {
UITextFieldViewModeNever, 重不出现
UITextFieldViewModeWhileEditing, 编辑时出现
UITextFieldViewModeUnlessEditing, 除了编辑外都出现
UITextFieldViewModeAlways 一直出现
} UITextFieldViewMode;
(10) //输入框中一开始就有的文字
text.text = @"一开始就在输入框的文字";
(11) //每输入一个字符就变成点 用于密码输入
text.secureTextEntry = YES;
(12) //是否纠错,纠正单词的拼写是否有误
text.autocorrectionType = UITextAutocorrectionTypeNo;
typedef enum {
UITextAutocorrectionTypeDefault, 默认
UITextAutocorrectionTypeNo, 不自动纠错
UITextAutocorrectionTypeYes, 自动纠错
} UITextAutocorrectionType;
(14) //再次编辑就清空
text.clearsOnBeginEditing = YES;
(15) //内容对齐方式
text.textAlignment = UITextAlignmentLeft;