通过更改约束常量使视图动画化

Mda*_*daG 5 animation autolayout nslayoutconstraint swift

我有一个datePicker,我想通过将其顶部约束更改为超级视图顶部来从底部进行动画显示。

我为其设置了IBOutlet,并允许在viewDidLoad上更改约束常量。

在此处输入图片说明

  override func viewDidLoad() {
    super.viewDidLoad()
    self.datePickerTopConstraint.constant = self.view.frame.size.height // I can set this to whatever and it will persist
  }
Run Code Online (Sandbox Code Playgroud)

但是,通过IBAction,我尝试将常量设置为另一个值,并且该值不会持续存在。

@IBAction func showDatePicker() {
    UIView.animateWithDuration(0.25, animations: {
      () -> Void in
      self.datePickerTopConstraint.constant = self.view.frame.size.height - self.datePicker.frame.size.height // Doesn't persist
      self.view.layoutIfNeeded()
    })
  }
Run Code Online (Sandbox Code Playgroud)

看来我可以扭转这种情况,并使datePicker出现在视图中(在viewDidLoad中)并在视图外进行动画处理,但不能让datePicker出现在视图外(如上例中所示)并在视图内部进行动画处理。我错过了什么?

编辑

通过将顶部约束常量设置为超级视图的高度I(出于某种原因,我不理解)还将日期选择器的高度设置为0,这反过来又使showDatePicker中的减法毫无意义。

Pet*_*sby 4

重构代码,以便在按钮的方法中首先计算出常量的新值,然后调用动画。将高度计算拉入它自己的函数中。我认为它self.datePicker.frame.size.height不存在并且结果为 0,但我会使用调试器检查这一点。

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    datePickerTopConstraint.constant = constantForDatePickerViewHeightConstraint()
    view.setNeedsLayout()

}


@IBAction func showDatePicker(button: UIButton) {

    // Check constraint constant
    if datePickerTopConstraint.constant == self.view.frame.size.height {

        // Date picker is NOT visible
        datePickerTopConstraint.constant = constantForDatePickerViewHeightConstraint()

    } else {
        // Date picker is visible
        datePickerTopConstraint.constant = self.view.frame.size.height
    }


    UIView.animateWithDuration(0.25,
        animations: {() -> Void in
        self.view.layoutIfNeeded()
    })
}

private func constantForDateOPickerViewHeightConstraint() -> CGFloat {

    var value : CGFloat = 200.0

    // Workout value you want to as the constant for the constraint.

    return value
}
Run Code Online (Sandbox Code Playgroud)