IOS中解決Keyboard遮蓋輸入的辦法

來源:互聯網
上載者:User

一般來說,鍵盤遮擋主要有這麼幾種情況,一個是遮住UITextView,還有就是遮住UITextField,一 般來說,比較推薦在UIScrollView或者UITableView裡加入textfield的控制項。但是有時也許難免。

在UITextView中

這個在蘋果官方文檔中的項目中給出了做法,首先是註冊觀察者監聽 UIKeyboardWillShow和WillHide事件

- (void)viewWillAppear:(BOOL)animated  {      [super viewWillAppear:animated];                [[NSNotificationCenter defaultCenter] addObserver:self                                               selector:@selector(keyboardWillShow:)                                                   name:UIKeyboardWillShowNotification                                                 object:nil];      [[NSNotificationCenter defaultCenter] addObserver:self                                               selector:@selector(keyboardWillHide:)                                                   name:UIKeyboardWillHideNotification                                                 object:nil];  }

實現自訂的方法

- (void)keyboardWillShow:(NSNotification *)aNotification  {      NSDictionary *userInfo = [aNotification userInfo];                CGRect keyboardRect = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];      NSTimeInterval animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];                CGRect newFrame = self.view.frame;      newFrame.size.height -= keyboardRect.size.height;                [UIView beginAnimations:@"ResizeTextView" context:nil];      [UIView setAnimationDuration:animationDuration];                self.view.frame = newFrame;                [UIView commitAnimations];  }

擷取鍵盤顯示的資訊,然後根據資訊對view的frame進行調整,然後WillHide方法就跟上面相 同,只不過把高度新高度改成+= keyboardRect.size.height就可以了,最後,移除觀察者:

- (void)viewDidDisappear:(BOOL)animated  {      [super viewDidDisappear:animated];                [[NSNotificationCenter defaultCenter] removeObserver:self                                                      name:UIKeyboardWillHideNotification                                                    object:nil];      [[NSNotificationCenter defaultCenter] removeObserver:self                                                      name:UIKeyboardWillShowNotification                                                    object:nil];  }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.