我有一个使用自动布局的登录视图。当我点击用户名文本文件输入一些信息时,视图会弹出键盘,然后键盘会阻塞一些UI。我想改变一些UI的框架信息时,弹出键盘在代码,但由于UI使用自动布局,所以设置UI的框架在代码不工作。
我该如何处理这种情况?
发布于 2014-10-27 06:25:41
应该将IBOutlet设置为要修改的约束,并在代码中更改其常量属性的值(如果需要,则为动画)。
发布于 2014-10-27 02:51:31
您需要动画一个NSLayoutConstraint的常量值。
所以你创造了这样的一个:
class ViewController: UIViewController {
var loginBox:UIView?;
var loginBoxTopConstraint:NSLayoutConstraint?;
override func viewDidLoad() {
...
self.initConstraints();
}
func initConstraints()
{
// init constraints here
}
...
}然后,您就会在下面这样的东西中加入这个约束:
func initConstraints()
{
...
self.loginBoxTopConstraint = NSLayoutConstraint(item: self.loginBox!, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 150.0);
self.view.addConstraint(self.loginBoxTopConstraint!);
}现在,当用户点击一个登录字段时,您的UITextField委托didBeginEditing就会被调用。这是将约束常量值动画化的地方:
func textFieldDidBeginEditing(textField: UITextField) {
...
self.loginBoxTopConstraint?.constant = 20.0; // was 150 before
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.view.layoutIfNeeded();
});
}当用户完成输入文本字段时,应该调用textFieldDidEnd委托方法:
func textFieldDidEndEditing(textField: UITextField) {
...
self.loginBoxTopConstraint?.constant = 150.0; // reset to 150
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.view.layoutIfNeeded();
});
}希望这能有所帮助。
https://stackoverflow.com/questions/26580351
复制相似问题