简体   繁体   English

使用自动布局约束Swift 2.1从中心到顶部对UIView进行动画处理

[英]Animate UIView from center to top using autolayout constraings swift 2.1

I want to animate UITextField from center to top of the view on a button click. 我想在单击按钮时从视图的中心到顶部为UITextField设置动画。 TextField has following constraints TextField具有以下约束

在此处输入图片说明

Following is the code to on button click to move textfiled to top. 以下是单击按钮以将文本文件移到顶部的代码。

 UIView.animateWithDuration(0.5) {
   self.txtfield.center.y = 10
  }

above code works, textfiled moved to top but when I go back and come to this view again textfield is again in center. 上面的代码有效,textfiled移至顶部,但是当我返回并再次进入此视图时,textfield再次位于中心。 I am new to swift I want that once textfield is moved to top it should stay on top. 我是新手,我想一旦文本字段移到顶部,它就应该放在顶部。

You should get a reference to the constraint in your code. 您应该在代码中获得对约束的引用。 Then you change the constant value of the constraint instead. 然后,您改为更改约束的常量值。

I have added the code to move the text field to top in viewDidLoad but you will of course have this code in your button action. 我已经添加了将文本字段移至viewDidLoad顶部的代码,但是您当然会在按钮操作中包含此代码。 You have to drag from the "Align Center Y" and into your view controller in order to create a reference to the constraint. 您必须从“对齐中心Y”拖动到视图控制器中,才能创建对约束的引用。 The reason why I subtract 10 is because your example and intention was to have a 10 points margin from the top. 我减去10的原因是因为您的榜样和意图是要从顶部获得10分的利润。 And take note that I "reversed" the first and second item like this: 并注意我像这样“颠倒”了第一和第二项:

在此处输入图片说明

Remember that when you use auto layout, the frame and center and the size of the views bounds get set by auto layout constraints. 请记住,使用自动布局时,边框和中心以及视图边界的大小是由自动布局约束设置的。

class ViewController: UIViewController {

    @IBOutlet weak var textFieldYAlignConstraint: NSLayoutConstraint!
    @IBOutlet weak var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

         UIView.animateWithDuration(1.2) { () -> Void in
        self.centeraligntConstraint.constant = -400
        self.view.layoutIfNeeded()// to animate layout constraint
    }

    }
}

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM