避免彈出鍵盤遮蔽輸入欄位

1 篇文章 / 0 new
author
避免彈出鍵盤遮蔽輸入欄位
apple 不像 android 一樣, 當輸入欄位被鍵盤遮住時, 系統會自動轉動畫面讓當前輸入欄位上移呈現, apple則必須要自己處理轉動動作. 因此若需做此處理, 首先在 layout 就必須加一層 UIScrollView 來做捲動處理. 接下來就是控制部分.
override func viewDidLoad() {
    super.viewDidLoad();
    //獲得浮出鍵盤事件
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil);
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil);
}
deinit {
    NotificationCenter.default.removeObserver(self);
}
//調整 scrollView 以免出鍵盤遮蔽輸入欄位
func keyboardWillShow(_ notification: NSNotification){
    let userInfo = notification.userInfo ?? [:]
    let kbSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
    let contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    scrollView.contentInset = contentInsets;        
    scrollView.scrollIndicatorInsets = contentInsets;
}
//scrollView 調回原位置
func keyboardWillHide(_ notification: NSNotification){
    let contentInsets = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0);
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;
}
Free Web Hosting