正如评论中提到的,当您安装了自动布局约束时,您不应该手动修改框架。相反,您需要更改约束以反映动画的最终结果。
以下是一个最小的工作示例。它创建一个按钮和一个文本字段,并最初将文本字段定位在按钮末端下方 58 点处。当您点击按钮时,文本字段顶部间距约束的常量从 58 减少到 8 以向上移动文本字段。
class ViewController: UIViewController {
var textFieldTopSpacingConstraint: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
// Create the button
let button = UIButton.buttonWithType(.System) as! UIButton
button.setTranslatesAutoresizingMaskIntoConstraints(false)
button.setTitle("Tap me!", forState: .Normal)
button.addTarget(self, action: "buttonTapped", forControlEvents: .TouchUpInside)
view.addSubview(button)
// Create the text field
let textField = UITextField()
textField.placeholder = "Enter text here"
textField.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(textField)
let views: [NSObject: AnyObject] = ["button": button, "textField": textField]
// Layout the button
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[button]-|", options: nil, metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[button(44)]", options: nil, metrics: nil, views: views))
// Layout the text field and remember its top spacing constraint
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[textField]-|", options: nil, metrics: nil, views: views))
textFieldTopSpacingConstraint = NSLayoutConstraint(item: textField, attribute: .Top, relatedBy: .Equal,
toItem: button, attribute: .Bottom, multiplier: 1, constant: 58) // The text field starts 58 points below the end of the button
view.addConstraint(textFieldTopSpacingConstraint!)
}
func buttonTapped() {
// Change to constant on the top spacing constraint to move the text field up
UIView.animateWithDuration(0.5) {
self.textFieldTopSpacingConstraint?.constant = 8 // The text field now starts 8 points below the end of the button
self.view.layoutIfNeeded()
}
}
}
通过 Interface Builder 设置约束后,您可以在视图控制器中为顶部间距约束创建一个出口,并使用它来修改文本字段的顶部空间。