今天下午写了个Demo,让键盘弹出时整个View上移,隐藏时整个View回到原位。用通知做的
1 #import "ViewController.h" 2 3 @interface ViewController () 4 @property(nonatomic, strong)UITextField *textView; 5 @property(nonatomic, strong)UIButton *btn; 6 @end 7 8 @implementation ViewController 9 10 - (void)viewDidLoad { 11 [super viewDidLoad]; 12 13 self.textView=[[UITextView alloc]init]; 14 self.textView.frame = CGRectMake(0, self.view.frame.size.height-500, self.view.frame.size.width, 200); 15 self.textView.text=@"请输入文字"; 16 self.textView.backgroundColor = [UIColor grayColor]; 17 self.btn = [[UIButton alloc]initWithFrame:CGRectMake(20, 20, 100, 100)]; 18 self.btn.backgroundColor = [UIColor blueColor]; 19 [self.view addSubview:self.btn]; 20 [self.view addSubview:self.textView]; 21 } 22 - (void)viewWillAppear:(BOOL)animated 23 { 24 //注册通知,监听键盘出现 25 [[NSNotificationCenter defaultCenter]addObserver:self 26 selector:@selector(handleKeyboardDidShow:) 27 name:UIKeyboardDidShowNotification 28 object:nil]; 29 //注册通知,监听键盘消失事件 30 [[NSNotificationCenter defaultCenter]addObserver:self 31 selector:@selector(handleKeyboardDidHidden) 32 name:UIKeyboardDidHideNotification 33 object:nil]; 34 [super viewWillAppear:YES]; 35 } 36 37 //监听事件 38 - (void)handleKeyboardDidShow:(NSNotification*)paramNotification 39 { 40 //获取键盘高度 41 NSValue *keyboardRectAsObject=[[paramNotification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey]; 42 43 CGRect keyboardRect; 44 [keyboardRectAsObject getValue:&keyboardRect]; 45 self.view.frame = CGRectMake(0,-20, self.view.frame.size.width, self.view.frame.size.height); 46 //self.textView.frame = CGRectMake(0, self.view.frame.size.height-500-keyboardRect.size.height, self.view.frame.size.width, 200); 47 //self.textView.frame = UIEdgeInsetsMake(0, 0,keyboardRect.size.height, 0); 48 } 49 - (void)didReceiveMemoryWarning { 50 [super didReceiveMemoryWarning]; 51 52 } 53 - (void)handleKeyboardDidHidden 54 { 55 self.view.frame = CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height); 56 //self.textView.frame = CGRectMake(0, self.view.frame.size.height-500, self.view.frame.size.width, 200); 57 //self.textView.contentInset=UIEdgeInsetsZero; 58 } 59 60 - (void)viewDidDisappear:(BOOL)animated 61 { 62 [[NSNotificationCenter defaultCenter] removeObserver:self]; 63 } 64 @end