2014-10-28 114 views
3

我在UIViewController中設置了一些可以在ios8上正常工作的佈局約束。但只要我在ios7我已經得到了以下錯誤運行:NSLayoutConstraints在ios7上崩潰而在ios8上崩潰

*** 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])) 

} 
} 

什麼是錯在我的代碼?我甚至可以知道在哪裏尋找一些錯誤,對我來說一切都很好。

+0

是否有被寫入控制檯任何不可滿足的約束? – BangOperator 2014-10-28 13:44:06

+0

不,只不過是斷言失敗信息 – Loadex 2014-10-28 15:28:56

+0

當你添加約束時,檢查一些視圖是否爲零大小 – dwery 2014-11-18 10:00:40

回答

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() 

} 
+0

這對我來說固定的東西。我更新了viewDidLayoutSubviews中的約束條件,並在iOS 7上發生崩潰,但不在iOS 8上發生。 – EarlyRiser 2015-07-28 21:48:40