當(dāng)鍵盤快速顯示時移動文本字段我正在使用Swift進(jìn)行iOS編程,我正在使用此代碼移動UITextField,但它不起作用。我keyboardWillShow正確調(diào)用該函數(shù),但文本字段不移動。我正在使用autolayout。override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);}deinit {
NSNotificationCenter.defaultCenter().removeObserver(self);}func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
//let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
var frame = self.ChatField.frame
frame.origin.y = frame.origin.y - keyboardSize.height + 167
self.chatField.frame = frame
println("asdasd")
}}
3 回答

守著一只汪
TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個贊
如果您正在使用自動布局,我假設(shè)您已將“ 底部空間”設(shè)置為“超級視圖” 約束。如果是這種情況,您只需更新約束的值即可。這是你用一點(diǎn)點(diǎn)動畫做到的。
func keyboardWasShown(notification: NSNotification) { let info = notification.userInfo! let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() UIView.animateWithDuration(0.1, animations: { () -> Void in self.bottomConstraint.constant = keyboardFrame.size.height + 20 })}
添加硬編碼20只是為了彈出鍵盤上方的文本字段。否則鍵盤的上邊距和文本字段的下邊距將會觸及。
鍵盤關(guān)閉后,將約束的值重置為其原始值。
- 3 回答
- 0 關(guān)注
- 644 瀏覽
添加回答
舉報
0/150
提交
取消