当键盘出现swift时移动文本字段 [英] Move textfield when keyboard appears swift
问题描述
我使用swift程序与IOS和我使用这段代码移动文本字段,但不工作,我正确调用keyboardWillShow的功能,但文本字段不移动..我使用autolayout
I'm using swift for program with IOS and i use this code for move the textfield, but does not work, I call correctly the function keyboardWillShow but the textfield doesn't move.. i'm using 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")
}
}
推荐答案
如果您使用的是Auto Layout,将底部空间到超视图约束设置为。如果是这种情况,你只需要更新约束的值。
If you're using Auto Layout, I assume you've set the Bottom Space to Superview constraint. If that's the case, you simply have to update the constraint's value. Here's how you do it with a little bit of animation.
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仅添加到弹出键盘上方的文本字段。否则键盘顶部边距和文本框底部边距将会接触。
The hardcoded 20 is added only to pop the textfield above the keyboard just a bit. Otherwise the keyboard's top margin and textfield's bottom margin would be touching.
键盘被关闭时,将约束值重置为原始值。
When the keyboard is dismissed, reset the constraint's value to its original one.
这篇关于当键盘出现swift时移动文本字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!