用到的变量
@IBOutlet weak var textField: UITextField!
var keyHeight = CGFloat() //键盘的高度
在viewDidLoad()中声明一个监听键盘事件
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self
let centerDefault = NSNotificationCenter.defaultCenter()
centerDefault.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: UIKeyboardWillShowNotification, object: nil)
}
//完成keyboardWillShow()
//同时键盘弹出时上移
func keyboardWillShow(aNotification: NSNotification) {
let userinfo: NSDictionary = aNotification.userInfo!
let nsValue = userinfo.objectForKey(UIKeyboardFrameEndUserInfoKey)
let keyboardRec = nsValue?.CGRectValue()
let height = keyboardRec?.size.height
self.keyHeight = height!
UIView.animateWithDuration(0.5, animations: {
var frame = self.view.frame
frame.origin.y = -self.keyHeight
self.view.frame = frame
}, completion: nil)
}
//键盘隐藏时恢复
func textFieldShouldEndEditing(textField: UITextField) -> Bool {
UIView.animateWithDuration(0.5, animations: {
var frame = self.view.frame
frame.origin.y = 0
self.view.frame = frame
}, completion: nil)
return true
}
网友评论