通过更改约束常量

时间:2015-12-28 13:23:46

标签: swift animation autolayout nslayoutconstraint

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

我设置了一个IBOutlet,并且在viewDidLoad上我可以更改约束常量。

enter image description here

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

然而,通过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()
    })
  }

似乎我可以反转这一点并让datePicker出现在视图中(在viewDidLoad中)并将其设置为视图外的动画,但不要让datePicker出现在视图之外(如上例所示)并在视图内部设置动画。我错过了什么?

修改

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

2 个答案:

答案 0 :(得分:3)

重新构造代码,以便在按钮的方法工作中首先计算常量的新值,然后调用动画。将高度计算拉入其自身的功能。我认为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
}

答案 1 :(得分:0)

试试这个:

func showDatePicker() {
    self.view.layoutIfNeeded()
    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()
    })
  }

您需要在动画块之前和块中调用layoutIfNeeded。现在正在正确计算视图。就像我说的那样,在viewDidLoad中设置任何约束也没有意义,如果你要在viewWillAppear中的任何地方进行设置。视图尚未在viewDidLoad中完成设置,因此没有可用的约束来正确设置。在动画块之前调用layoutIfNeeded修复了这个错误,无论如何你都需要它,所以它也可以在将来正确计算。

相关问题