Swift讓輸出框跟隨鍵盤彈起防止輸出輸出法擋住輸出框問題。本站提示廣大學習愛好者:(Swift讓輸出框跟隨鍵盤彈起防止輸出輸出法擋住輸出框問題)文章只能為提供參考,不一定能成為您想要的結果。以下是Swift讓輸出框跟隨鍵盤彈起防止輸出輸出法擋住輸出框問題正文
第一步: 新建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: { _ in self.view.frame = CGRectMake(0,-deltaY,self.view.bounds.width,self.view.bounds.height) self.keyBoardNeedLayout = false self.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: { _ in self.view.frame = CGRectMake(0,deltaY,self.view.bounds.width,self.view.bounds.height) self.keyBoardNeedLayout = true self.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讓輸出框跟隨鍵盤彈起防止輸出輸出法擋住輸出框問題,希望對大家有所協助,假如大家有任何疑問請給我留言,會及時回復大家的。在此也十分感激大家對網站的支持!