第一步: 新建Controller
在Xcode選擇File → New → File → Cocoa Touch Class
新建LoginViewController繼承自UIViewController
第二步:創建兩個UITextField
passwordInput: UITextField // 密碼輸入框
accountInput: UITextField // 帳號輸入框
第三步:添加鍵盤KVO
在viewDidLoad方法添加下面兩行代碼
//當鍵盤彈起的時候會向系統發出一個通知,//這個時候需要注冊一個監聽器響應該通知NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.keyboardWillShow(_:)), name:UIKeyboardWillShowNotification, object: nil)//當鍵盤收起的時候會向系統發出一個通知,//這個時候需要注冊另外一個監聽器響應該通知NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.keyboardWillHide(_:)), name:UIKeyboardWillHideNotification, object: nil)
添加全局控制參數
因為連續在兩個或多個textfield之間切換時候,只會發送UIKeyboardWillShowNotification鍵盤顯示通知,而不會發送UIKeyboardWillHideNotification鍵盤隱藏通知,這就需要一個全局參數控制鍵盤只在第一次點擊輸入框時候界面上移,該參數變為false,光標移到另一個輸入框時界面不再變化。當關閉鍵盤時候,界面下移,并將這個參數恢復為默認值。
在類的第一行聲明該變量:
var keyBoardNeedLayout: Bool = true
添加兩個方法分別相應鍵盤彈起和鍵盤隱藏
鍵盤彈起響應
func keyboardWillShow(notification: NSNotification) {print("show")if let userInfo = notification.userInfo,value = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue,duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double,curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? UInt {let frame = value.CGRectValue()let intersection = CGRectIntersection(frame, self.view.frame)let deltaY = CGRectGetHeight(intersection)if keyBoardNeedLayout {UIView.animateWithDuration(duration, delay: 0.0,options: UIViewAnimationOptions(rawValue: curve),animations: { _ inself.view.frame = CGRectMake(0,-deltaY,self.view.bounds.width,self.view.bounds.height)self.keyBoardNeedLayout = falseself.view.layoutIfNeeded()}, completion: nil)}}}
鍵盤隱藏響應
func keyboardWillHide(notification: NSNotification) {print("hide")if let userInfo = notification.userInfo,value = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue,duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double,curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? UInt {let frame = value.CGRectValue()let intersection = CGRectIntersection(frame, self.view.frame)let deltaY = CGRectGetHeight(intersection)UIView.animateWithDuration(duration, delay: 0.0,options: UIViewAnimationOptions(rawValue: curve),animations: { _ inself.view.frame = CGRectMake(0,deltaY,self.view.bounds.width,self.view.bounds.height)self.keyBoardNeedLayout = trueself.view.layoutIfNeeded()}, completion: nil)}}
更進一步
如果輸入框吸底,y的位移可以用-deltaY
self.view.frame = CGRectMake(0,-deltaY,self.view.bounds.width,self.view.bounds.height)
但是如果輸入框在偏上的位置就有可能導致某個輸入框移出界面視界,這時候可以把位移寫成deltaY/2或者deltaY/4等,自己去嘗試吧。
以上所述是小編給大家介紹的Swift讓輸入框跟隨鍵盤彈起避免輸入輸入法擋住輸入框問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VEVB武林網網站的支持!
新聞熱點
疑難解答