为什么我的约束不能正常工作?

时间:2016-06-26 17:19:44

标签: ios swift autolayout

我在Interface Builder中有一些约束,所以当视图加载时我删除所有约束并从代码中添加新约束但是它们搞砸了

这是我的代码(我知道它是带有标志等的坏样式代码,对不起,但问题是为什么它使布局错误):

 override func viewWillAppear(animated: Bool) {

    super.viewWillAppear(true)

    self.view.layoutIfNeeded()
    self.view.setNeedsUpdateConstraints()
    self.view.layoutIfNeeded()
            self.buttonsArray.forEach() { button in
                NSLayoutConstraint(item: button, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1, constant: 0).active = true

                NSLayoutConstraint(item: button, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1, constant: 0).active = true

                NSLayoutConstraint(item: button, attribute: .Height, relatedBy: .Equal, toItem: self.view, attribute: .Height, multiplier: 0.15, constant: 0).active = true
            }
}

var flagForOriginalConstraints = 0
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if flagForOriginalConstraints == 0 {
    self.constraintsArray = self.view.constraints
    self.flagForOriginalConstraints += 1
        return
    }
    if flagForOriginalConstraints == 1 {
        self.view.removeConstraints()
        self.flagForOriginalConstraints += 1
         return
    } 
}

1 个答案:

答案 0 :(得分:0)

删除此处的返回

var chart = d3.select("#chart").append("svg")
  .attr("width", width).attr("height", height);
  .append("g")
  .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

好像第一次你只是递增flagForOriginalConstraints计数然后函数返回