所以我有以下代码:
//MARK: - Textfield delegate Methods
func textFieldDidBeginEditing(textField: UITextField)
{
// update view based on updates in the constraints
self.view.layoutIfNeeded()
//perform animation to grow the dockview
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.dockViewHeightConstraint.constant = self.keyBoardHeight + 60
self.view.layoutIfNeeded()
}, completion: nil)
}
和
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
}
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)
keyBoardHeight = contentInsets.bottom
}
}
我要做的是以下内容。当用户点击文本字段时,键盘应该打开,我所做的视图应该向上移动。
我从键盘中获得了由NSNotification触发的keyboardWillShow
函数的高度。
问题如下:当我运行代码时,在textFieldDidBeginEditing
之前调用NSNotification
,使我的self.keyBoardHeight值为0(初始值)。有没有办法在按下textField之前调用NSNotification
部分?
答案 0 :(得分:0)
在viewController中设置一个isKeyboardShown标志以跟踪键盘是否显示,与元素“myElement”相交的高度可以在fieldMovement属性中捕获,如下所示
if !isKeyboardShown
{
if let info = notification.userInfo
{
if fieldMovement == nil
{
let window = UIApplication.sharedApplication().keyWindow
var keyboardEndRect = CGRectZero
//Get frame of keyboard view object
((info[UIKeyboardFrameEndUserInfoKey] as! NSValue)).getValue(&keyboardEndRect)
/* Convert the frame from the window's coordinate system to our view's coordinate system */
keyboardEndRect = view.convertRect(keyboardEndRect, fromView: window)
/* Find out how much of our view is being covered by the keyboard */
fieldMovement = CGRectIntersection(myElement.frame, keyboardEndRect).height
}
//Get animation duration of keyboard
var animationDuration: NSTimeInterval = 0
(info[UIKeyboardAnimationDurationUserInfoKey] as! NSValue).getValue(&animationDuration)
// Move views up by intersected height
UIView.animateWithDuration(animationDuration)
{
//animate your objects here
}
}
isKeyboardShown = true
}