NSLayoutConstraints在iOS7上崩溃但在iOS8上不会

3

我在一个UIViewController中设置了一些布局约束,这在iOS8上运行良好。但是当我在iOS7上运行时,出现了以下错误:

*** Assertion failure in -[UIView layoutSublayersOfLayer:], /SourceCache/UIKit_Sim/UIKit-2935.137/UIView.m:8803

这是我的代码:
class DatacenterIndicatorViewController: UIViewController {

let sideMargins:Float = 12.0   
var dataCenterPollingLabel:UILabel = UILabel()
var dataCenterAlarmLabel:UILabel = UILabel()

//MARK: - Life cycle
override func viewDidLoad() {
    super.viewDidLoad()
    self.view.addSubview(dataCenterPollingLabel)
    self.view.addSubview(dataCenterAlarmLabel)
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    self.reloadData()
}

func reloadData() {
    self.setupAlarmLabel()
    self.setupPollingLabel()
    self.generateConstraints()
}

func setupPollingLabel() {
   // some graphic setup
}

func setupAlarmLabel() {
     // some graphic setup
}

func generateConstraints() {
    self.dataCenterPollingLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
    self.dataCenterAlarmLabel.setTranslatesAutoresizingMaskIntoConstraints(false)

    self.view.addConstraint(NSLayoutConstraint(item: dataCenterPollingLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0))
    self.view.addConstraint(NSLayoutConstraint(item: dataCenterAlarmLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0))
    self.view.addConstraint(NSLayoutConstraint(item: dataCenterAlarmLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: dataCenterPollingLabel, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 0.0))
    self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(NSString(format:"H:|-==%f-[dataCenterPollingLabel]-==%f-[dataCenterAlarmLabel]-==%f-|", sideMargins, sideMargins, sideMargins), options: NSLayoutFormatOptions.allZeros, metrics: nil, views: ["dataCenterPollingLabel": dataCenterPollingLabel, "dataCenterAlarmLabel": dataCenterAlarmLabel]))

}
}

我的代码出了什么问题?我甚至不知道去哪里找错误,所有东西看起来都很好。

控制台中是否有任何不可满足的约束条件被写入? - BangOperator
不,仅仅是断言失败的消息。 - Loadex
当您添加约束时,请检查某个视图是否具有零大小。 - dwery
为什么在iOS7中可以发生,但在iOS8中却不行? - Loadex
你找到问题出在哪了吗?我这里也遇到了同样的问题。 - Thomas Keuleers
仍在寻找答案,如果我找到了什么,我会更新这篇文章。你应该检查在storyboard中是否勾选了边距选项。 - Loadex
1个回答

12

我在iOS 7版本中遇到了同样的问题。在viewDidLayoutSubviews方法的末尾调用self.view.layoutIfNeeded()函数而不是super.viewDidLayoutSubviews()函数可以解决这个问题。

代码片段:

override func viewDidLayoutSubviews() {

    // Your statements
    self.reloadData()

    //Write the below statement at the end of the function
    self.view.layoutIfNeeded()

}

这对我解决了问题。我正在viewDidLayoutSubviews中更新约束,在iOS 7上崩溃但在iOS 8上没有。 - EarlyRiser

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接