UITextField详解:1-UITextField的基本属性
UITextField是iOS开发中用户交互的一个重要控件,常用于获取用户的文字输入,例如用户登录时使用的用户名输入框、密码输入框等。本章节我们介绍一下UITextField的基本属性和用法。
UITextField的文本相关属性
UITextField可以用于获取用户的文字输入,因此,通过其中的text属性我们可以获取到用户输入的文字。另外,通过placeholder属性可以设置UITextField对象的占位符文字,当用户输入文字时,占位符文字会自动消失。
- 获取文本框中的文字。
@property(nullable, nonatomic,copy) NSString *text;
- 占位符。通常在手机App的用户输入框中,都会有浅色的占位字,告诉用户“请输入用户名”或者“请输入密码”。
@property(nullable, nonatomic,copy) NSString *placeholder;
- 字体颜色
@property(nullable, nonatomic,strong) UIColor *textColor;
- 字体大小
@property(nullable, nonatomic,strong) UIFont *font;
- 文本对齐方式。文本框中的文字还可以设置对齐方式,一般常用的如居左、居中或居右。
@property(nonatomic) NSTextAlignment textAlignment;
UITextField的外观属性
- UITextField的背景颜色。
@property(nullable, nonatomic,copy) UIColor *backgroundColor;
- UITextField的边框样式。borderStyle有4种常见的样式,分别为:无边框UITextBorderStyleNone、线形边框UITextBorderStyleLine、带阴影效果的边框UITextBorderStyleBezel以及圆角边框UITextBorderStyleRoundedRect
@property(nonatomic) UITextBorderStyle borderStyle;
其他属性
- 设置输入文本时弹出的键盘类型(默认键盘、数字键盘、 数字+符号键盘等等),例如当我们希望用户输入的是电话号码时,最好弹出数字键盘,这样便于用户输入。
@property(nonatomic) UIKeyboardType keyboardType;
- 键盘弹出后的键盘返回键类型,例如:当键盘返回键类型取值为UIReturnKeyDefault以及UIReturnKeyGo时,弹出键盘的样式对比。
@property(nonatomic) UIReturnKeyType returnKeyType;
- 设置输入框输入的字母是否大写
@property(nonatomic) UITextAutocapitalizationType autocapitalizationType;
- 当开始编辑时,是否删除textField里面的所有字符串。
@property(nonatomic) BOOL clearsOnBeginEditing;
UITextField的创建
当我们需要创建UITextField类的对象时,既可以使用代码的方式创建,也可以使用Xib的方式创建,使用代码方式创建可以设置的属性会更加完整一些。
- 使用代码方式创建一个UITextField类型的对象,并对其属性进行设置。
- (void)viewDidLoad {
[super viewDidLoad];
//创建一个UITextField对象,并对样式和属性进行设置
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(50, 50, 250, 50)];
textField.backgroundColor = [UIColor whiteColor];
textField.placeholder = @"欢迎访问99iOS";;
textField.textAlignment = NSTextAlignmentCenter;
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.clearsOnBeginEditing = YES;
textField.keyboardType = UIKeyboardTypeDefault;
textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
textField.returnKeyType =UIReturnKeyDone;
textField.clearsOnInsertion = YES;
[self.view addSubview:textField];
}
运行效果:
- 使用Xib的方式创建UITextField对象。当在Storyboard中添加UITextField控件时,我们可以发现其高度Height是被限制在30px的,这在使用过程中就没有使用代码创建UITextField对象方便。除此之外,其余有关UITextField的属性与使用代码创建并无二异。
示例代码
https://github.com/99ios/7.7.1
文章发布时间为: November 29th , 2016 at 11:15 pm
最后编辑时间为: September 14th , 2017 at 09:30 am
本文由 99ios 创作,转载请注明出处
最后编辑时间为: September 14th , 2017 at 09:30 am
本文由 99ios 创作,转载请注明出处