我试图用 UITextField 和 UIButton 制作一个 UIView - 就像聊天应用程序一样。
我想检测出现在屏幕上的键盘级别,并根据它改变UIView高度约束。
我该怎么做?
现在我有了这个
@IBOutlet weak var messageTextField: UITextField!
@IBOutlet weak var bottomBarConstrains: NSLayoutConstraint!
override func viewDidLoad()
{
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
@IBAction func sendAction(sender: AnyObject)
{
messageTextField.resignFirstResponder();
}
func keyboardWillShow(notification: NSNotification)
{
var info = notification.userInfo!
let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let duration = info[UIKeyboardAnimationDurationUserInfoKey] as! Double
UIView.animateWithDuration(duration, delay: 2, options: UIViewAnimationOptions.CurveEaseIn, animations:
{ () -> Void in
self.bottomBarConstrains.constant = keyboardFrame.size.height;
},
completion: nil);
}
func keyboardWillHide(notification: NSNotification)
{
var info = notification.userInfo!
let duration = info[UIKeyboardAnimationDurationUserInfoKey] as! Double
UIView.animateWithDuration(duration, animations: { () -> Void in
self.bottomBarConstrains.constant = 0;
})
}
但它没有动画
答案 0 :(得分:2)
如果要为更改的约束设置动画,则需要在使用该约束的视图上使用layoutIfNeeded
方法。此方法强制视图更改布局子视图,但仅在需要时才更改。由于约束更改不会自动强制更改视图位置,因此需要调用此方法。因此,如果您的messageTextView
是self.view
的子视图,请使用:
self.bottomBarConstrains.constant = keyboardFrame.size.height
UIView.animateWithDuration(duration, delay: 2, options: .CurveEaseIn, animations: {
self.view.layoutIfNeeded()
}, completion: nil);
答案 1 :(得分:2)
更改KeyBoard打开和隐藏的代码,如下所示,打开KeyBoard时删除延迟,
func keyboardWillShow(notification: NSNotification)
{
var info = notification.userInfo!
let keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let duration = info[UIKeyboardAnimationDurationUserInfoKey] as! Double
self.bottomBarConstrains.constant = keyboardFrame.size.height
UIView.animateWithDuration(duration, animations: { () -> Void in
self.messageTextField.layoutIfNeeded()
self.view.layoutIfNeeded()
})
}
func keyboardWillHide(notification: NSNotification)
{
var info = notification.userInfo!
let duration = info[UIKeyboardAnimationDurationUserInfoKey] as! Double
self.bottomBarConstrains.constant = 0;
UIView.animateWithDuration(duration, animations: { () -> Void in
self.messageTextField.layoutIfNeeded()
self.view.layoutIfNeeded()
})
}
输出: