无法以编程方式移动 UITextView

Cannot move UITextView programmatically

这是我的问题,我想为我的登录屏幕制作动画,这是一个基本屏幕,2 个 UITextView 和 2 个按钮(登录和注册)

我想让我的用户名字段在应用程序启动时显示在屏幕外并为其设置动画,所以这是我的代码:

override func viewWillAppear(animated: Bool) {
    self.navigationController?.navigationBarHidden = true
    print (usernameField.center.x)

    usernameField.center.x -= view.bounds.width
    print (view.bounds.width)
    print (usernameField.center.x)

}

这是输出:

300.0
375.0
-75.0

所以我的 usernameField 的最终 x 是 -75.0,但在所有情况下它都在我的应用程序中居中。

我认为这是因为我在 Storyboard 中对其应用了约束? (建议将按钮和文本视图居中的约束条件)

感谢您的帮助

编辑: 删除约束并没有解决我的问题..

您将需要参考保持前导 space 和直接 neighbour/margin 的约束。然后为该约束的常量 属性 设置适当的值。然后要制作动画,您需要调用 动画块中的 layoutIfNeeded 方法。

首先确保您的视图超出范围并位于视图的左侧。

为约束说一个出口-

@IBOutlet weak var constraint : NSLayoutConstraint!

override func animateIn(){
  //Do any pending layout
  self.view.layoutIfNeeded()
  constraint.constant += 100 //<-- set appropriate value for your case
  //Animate the constraint change to bring in the button into the screen

  UIView.animateWithDuration(0.2, animations: {
    self.view.layoutIfNeeded()
})

}

参考: How do I animate constraint changes?