2017-02-21 78 views
-1

我想通过修改键盘高度将底部约束修改为键盘出现时将视图向上。但返回给我的键盘高度是不同的。键盘高度在出现时会有所不同

当我点击模拟器中的文本框时,键盘高度为302。当我尝试打开和关闭软件键盘时,它会在键盘出现时显示260。这是为什么发生?

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FriendsViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil) 

func keyboardWillShow(notification: NSNotification) { 
    print("Keyboard appearing") 
    guard let keyboardHeight = (notification.userInfo! as NSDictionary).objectForKey(UIKeyboardFrameBeginUserInfoKey)?.CGRectValue.size.height else { 
     return 
    } 
    bottomConstraint.constant = keyboardHeight 
    print("keyboard height : \(keyboardHeight)") 
    self.view.layoutIfNeeded() 
} 

260的高度实际上是正确的高度,因为它完美地调整了我的视角。随着302的高度,我的观点被抵消得太多了。

我认为的布局是。 UITextField位于顶部,其后是UITableView

+0

您正在使用的设备? –

+0

模拟iPhone 7 –

+0

好吧,让我在这里检查你的代码,等待。 –

回答

0

问题是你正在看UIKeyboardFrameBeginUserInfoKey。你想看的是UIKeyboardFrameEndUserInfoKey

+0

而你的代码还有其他问题。您需要将窗口坐标转换为本地坐标,而且您不需要对键盘高度进行任何假设,而只需查看键盘_top_的位置即可。 – matt

+0

感谢哥们。:) –

0

Matt合理修正的应答,

他是正确的,你需要使用UIKeyboardFrameEndUserInfoKey而不是UIKeyboardFrameBeginUserInfoKey因为

  1. UIKeyboardFrameEndUserInfoKey根据您已在设置中设置的使用偏好给你的最终高度。

  2. UIKeyboardFrameEndUserInfoKey回报你的高度的两倍第一个是没有语言的预测,你可以看到键盘和下一个谓语以上,如果它是从设置,但UIKeyboardFrameBeginUserInfoKey回报没有预测键激活。

上切换身高在iPhone 5s

enter image description here

+0

当我点击'UITextField'时,它仍然在iPhone 7上显示'302'的较大高度。只有当我打开和关闭软件键盘时,它才能够显示'260的正确高度' –

+0

@MaTaKazer看到我在答案中添加的图像,这是我切换软件键盘时得到的输出。我检查了'5s'这就是为什么它的'216&253'不是'260&302'。 –

+0

是的,当我在模拟器中切换软件键盘时,我得到2个值。但实际上,用户会点击'UITextField',这会让我返回错误的高度。 –

0

这是我在SWIFT 2 如何做到第一添加这个功能:

// Lifting the view up 
func animateViewMoving (up:Bool, moveValue :CGFloat){ 
    let movementDuration:NSTimeInterval = 0.3 
    let movement:CGFloat = (up ? -moveValue : moveValue) 
    UIView.beginAnimations("animateView", context: nil) 
    UIView.setAnimationBeginsFromCurrentState(true) 
    UIView.setAnimationDuration(movementDuration) 
    self.view.frame = CGRectOffset(self.view.frame, 0, movement) 
    UIView.commitAnimations() 
} 

,然后实现UITextFieldDelegate

// MARK: - UITextFieldDelegate 

func textFieldShouldReturn(textField: UITextField) -> Bool { 
    // Hide the keyboard. 
    textField.resignFirstResponder() 
    return true 
} 

func textFieldDidEndEditing(textField: UITextField) { 
    animateViewMoving(false, moveValue: 100) 
    textField.resignFirstResponder() 
} 

func textFieldDidBeginEditing(textField: UITextField) { 
    animateViewMoving(true, moveValue: 100) 
} 

你也可以键盘这样的确切高度:

var viewLiftUpValue : CGFloat 

func keyboardWillShow(notification:NSNotification) { 

     let userInfo:NSDictionary = notification.userInfo! 
     let keyboardFrame:NSValue = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey) as! NSValue 
     let keyboardRectangle = keyboardFrame.CGRectValue() 
     let keyboardHeight = keyboardRectangle.height 
     viewLiftUpValue = keyboardHeight 
    } 

,然后把它交给animateViewMoving()功能