鍵盤彈出與隱藏對TextView的影響

今天下午寫了個Demo,讓鍵盤彈出時整個View上移,隱藏時整個View回到原位。用通知作的app

 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
View Code
相關文章
相關標籤/搜索