監聽鍵盤工作,避免擋住文字輸入

- (void)viewDidLoad 

    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
    self.textView=[[UITextView alloc]initWithFrame:self.view.frame]; 
    self.textView.text=@"請輸入文字"; 
    [self.view addSubview:self.textView]; 

 
- (void)didReceiveMemoryWarning 

    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 

 
- (void)viewWillAppear:(BOOL)animated 

    //註冊通知,監聽鍵盤出現 
    [[NSNotificationCenter defaultCenter]addObserver:self 
                                            selector:@selector(handleKeyboardDidShow:) 
                                                name:UIKeyboardDidShowNotification 
                                              object:nil]; 
    //註冊通知,監聽鍵盤消失事件 
    [[NSNotificationCenter defaultCenter]addObserver:self 
                                            selector:@selector(handleKeyboardDidHidden) 
                                                name:UIKeyboardDidHideNotification 
                                              object:nil]; 
    [super viewWillAppear:YES]; 

 
//監聽事件 
- (void)handleKeyboardDidShow:(NSNotification*)paramNotification 

    //獲取鍵盤高度 
    NSValue *keyboardRectAsObject=[[paramNotification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey]; 
     
    CGRect keyboardRect; 
    [keyboardRectAsObject getValue:&keyboardRect]; 
     
    self.textView.contentInset=UIEdgeInsetsMake(0, 0,keyboardRect.size.height, 0); 

 
- (void)handleKeyboardDidHidden 

    self.textView.contentInset=UIEdgeInsetsZero; 

 
- (void)viewDidDisappear:(BOOL)animated 

    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
發佈了26 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章