2016-02-13 88 views
1

我有下面的课。我基本上添加NSNotification来检查键盘是否启动。如果键盘弹起,我更改按钮的框架以将其定位在键盘的顶部。我想我以正确的方式做到了这一点,但按钮显然不动。可能是什么问题呢?当键盘弹出时移动UIButton

class vc: UIViewController { 
var previousButton: UIButton! 
var nextButton: UIButton! 

override func viewDidLoad() { 
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil) 
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil) 

    previousButton = UIButton(frame: CGRectMake(margin + 20, containerView.frame.size.height + 10, 80, 30)) 
     previousButton.setImage(UIImage(named: "previous"), forState: .Normal) 
     previousButton.addTarget(self, action: "previousButtonPressed2:", forControlEvents: .TouchUpInside) 

     nextButton = UIButton(frame: CGRectMake(self.view.frame.width - margin - 80 - 20, containerView.frame.size.height + 10 , 80, 30)) 
     nextButton.setImage(UIImage(named: "next"), forState: .Normal) 
     nextButton.addTarget(self, action: "nextButtonPressed2:", forControlEvents: .TouchUpInside) 
     self.view.addSubview(previousButton) 
     self.view.addSubview(nextButton) 

} 

    func keyboardWillShow(notification: NSNotification) { 
     if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() { 
      previousButton = UIButton(frame: CGRectMake(10 + 20, self.view.frame.size.height - keyboardSize.height - 40, 80, 30)) 
     } 
    } 

    func keyboardWillHide(notification: NSNotification) { 
     if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() { 
       previousButton = UIButton(frame: CGRectMake(10 + 20, self.view.frame.size.height - 40, 80, 30)) 
     } 
    } 
} 

回答

2

您应该检查在keyboardWillShow:方法,而不是UIKeyboardFrameBeginUserInfoKeyUIKeyboardFrameEndUserInfoKey关键。这同样适用于keyboardWillHide:方法:

func keyboardWillShow(notification: NSNotification) { 
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() { 
     previousButton = UIButton(frame: CGRectMake(10 + 20, self.view.frame.size.height - keyboardSize.height - 40, 80, 30)) 
    } 
} 

func keyboardWillHide(notification: NSNotification) { 
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() { 
      previousButton = UIButton(frame: CGRectMake(10 + 20, self.view.frame.size.height - 40, 80, 30)) 
    } 
} 

UIKeyboardFrameBeginUserInfoKey允许你从键盘动画开始前获得键盘的框架,当你真正需要的键盘的框架,当键盘在屏幕完全可见。该值可以使用UIKeyboardFrameBeginUserInfoKey键进行检索。

+0

我试过了,不幸的是没有区别。 – Kahsn

+0

你能告诉我'CGRect'类型是如何实现'height'(你正在使用'keyboardSize.height')属性的吗?我假设你添加了扩展名 - 你能确认它能正常工作吗? –

+0

高度在CGRect的类型中正确实施。它只是从我的代码中的变量keyboardSize计算出来的。 – Kahsn