标签:
在viewController.h中加入代理
#import <UIKit/UIKit.h> @interface WJJRootViewController : UIViewController <span style="color:#FF0000;"><UITextFieldDelegate></span> @end
viewController.m中代码展示
#import "WJJRootViewController.h" @interface WJJRootViewController (){ <span style="color:#FF0000;">UITextField * _textField;</span> } @end @implementation WJJRootViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor greenColor]; // Do any additional setup after loading the view. _textField = [[UITextField alloc] initWithFrame:CGRectMake(40, 40, 240, 40)]; _textField.borderStyle = UITextBorderStyleRoundedRect; _textField.placeholder = @"请输入:"; _textField.clearButtonMode = UITextFieldViewModeAlways; _textField.keyboardType = UIKeyboardTypeDefault; _textField.returnKeyType = UIReturnKeyGo; <span style="color:#FF0000;"> //设置textField的代理 要让viewController为他收起键盘 _textField.delegate = self;</span> /* //自定义键盘 可以看出来自定义键盘只与高度有关 其他不影响自定义键盘的位置大小 UIView * keyboardView = [[UIView alloc] initWithFrame:CGRectMake(0, 1, 1, 100)]; keyboardView.backgroundColor = [UIColor redColor]; //把view赋值给inputView _textField.inputView = keyboardView; //设置二级键盘 UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(1, 1, 320, 20)]; label.text = @"男"; label.backgroundColor = [UIColor grayColor]; _textField.inputAccessoryView = label; */ [self.view addSubview:_textField]; } //方法标记位 #pragma mark UITextFieldDelagate //下面的方法就是UITextFieldDelegate中常用的委托方法 //文本框将要开始编辑时调用 - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{ return YES; } //文本编辑开始的时候调用 - (void)textFieldDidBeginEditing:(UITextField *)textField{ } //文本框将要结束编辑时调用 - (BOOL)textFieldShouldEndEditing:(UITextField *)textField{ return YES; } //文本框结束编辑时调用 - (void)textFieldDidEndEditing:(UITextField *)textField{ } //当按下return键时调用的方法 - (BOOL)textFieldShouldReturn:(UITextField *)textField{ //让textField失去第一响应者 即收起键盘 [textField resignFirstResponder]; return YES; } //每个viewController都会有的触摸方法 点击空白处收起键盘 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ //第一种方法 //[_textField resignFirstResponder]; //第二种方法 原理:编辑textField的时候相当于编辑viewController 所以设置 //viewController结束编辑 [self.view endEditing:YES]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
效果图如下
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/qq1791422018/article/details/47028367