键盘高度被称为
所以我有以下代码:键盘高度被称为
//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
函数获得键盘的高度。
问题是:当我运行代码时,在NSNotification
之前调用textFieldDidBeginEditing
,使self.keyBoardHeight值为0(初始值)。在按下textField之前,我可以调用NSNotification
部件吗?
建立一个isKeyboardShown标志在你的viewController跟踪键盘是否显示与否,这与你的元素“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
}
这是如何让我的NSNotification在textFieldDidBeginEditing之前熄灭的? – SoundShock
您不需要实现textFieldDidBeginEditing:方法keyboardWillShow和keyboardWillHide通知从键盘接收而不是textField – Pranshu
你必须使用高度TPKeyboardAviding第三方库 – Birendra
只是给一个更好的初步猜测,而不是0. – zcui93
这是链接https://github.com/michaeltyson/TPKeyboardAvoiding – Birendra