- //姓名输入域
- UITextField *nameField =[[UITextField alloc] initWithFrame:CGRectMake(30, 30, 200, 44)];
- nameField.tag = 100;
- nameField.delegate = self;
- //默认文字
- nameField.placeholder = @"name";
- nameField.font = [UIFont systemFontOfSize:16.0f];
- nameField.textColor = [UIColor blackColor];
- //输入框的背景图片(还可以选择设置背景颜色)
- nameField.background = [UIImage imageNamed:@"textFieldBackgroundImage"];
- //nameField.backgroundColor = [UIColor lightGrayColor];
- //清除按钮
- nameField.clearButtonMode = UITextFieldViewModeAlways;
- //键盘类型
- nameField.keyboardType = UIKeyboardTypeDefault;
- [self.view addSubview:nameField];
- 电话输入域
- UITextField *phoneField =[[UITextField alloc] initWithFrame:CGRectMake(30, nameField.frame.origin.y + nameField.bounds.size.height+10, 200, 44)];
- phoneField.tag = 101;
- phoneField.delegate = self;
- phoneField.placeholder = @"phone";
- phoneField.keyboardType = UIKeyboardTypeDecimalPad;
- phoneField.clearButtonMode = UITextFieldViewModeAlways;
- [self.view addSubview:phoneField];
- //邮箱输入域
- UITextField *emailField =[[UITextField alloc] initWithFrame:CGRectMake(30, phoneField.frame.origin.y + phoneField.bounds.size.height + 10, 200, 44)];
- emailField.tag = 102;
- emailField.delegate = self;
- emailField.placeholder = @"email";
- emailField.keyboardType = UIKeyboardTypeEmailAddress;
- emailField.clearButtonMode = UITextFieldViewModeAlways;
- [self.view addSubview:emailField];
1.点击键盘的return来隐藏键盘
这个方法需要在相应的.h文件文件中实现UITextFieldDelegate协议。并在.m文件中添加如下方法
- - (BOOL)textFieldShouldReturn:(UITextField *)textField
- {
- [textField resignFirstResponder];
- return YES;
- }
2.点击界面空白处来隐藏键盘
这个方法的实现主要是给当前的view增加点击事件,并未点击事件增加相应的处理方法,此处是为了隐藏键盘,所以我们可以在点击事件对应的方法中让UITextField放弃第一响应者。
- - (void)dismissKeyboard
- {
- NSArray *subViews = [self.view subviews];
- for (id inputText in subViews) {
- if ([inputText isKindOfClass:[UITextField class]]) {
- if ([inputText isFirstResponder]) {
- [inputText resignFirstResponder];
- }
- }
- }
- }
为当前的view增加点击事件
- UITapGestureRecognizer *dismissKeyboardTap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
- [self.view addGestureRecognizer: dismissKeyboardTap];
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
- {
- switch (textField.tag) {
- case 100://name
- {
- NSLog(@"this is nameField");
- //添加校验name的代码
- break;
- }
- case 101://phone
- {
- NSLog(@"this is phoneField");
- //添加校验phone的代码
- break;
- }
- case 102://email
- {
- NSLog(@"this is emailField");
- //添加校验email的代码
- break;
- }
- default:
- break;
- }
- return YES;
- }
本文链接:http://my.oschina.net/yulei1943/blog/293201
网页标题:iOS开发之UITextField
当前路径:http://www.shufengxianlan.com/qtweb/news14/325464.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联