国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

ViewDidLoad中使用NSLayoutConstraint產生的問題解決

2019-11-09 15:28:53
字體:
來源:轉載
供稿:網友

Demo Code:

UIView *v = [[UIView alloc] initWithFrame:CGRectZero];  v.backgroundColor = [UIColor redColor];  v.translatesAutoresizingMaskIntoConstraints = NO;  [self.view addSubview:self.v];      NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:v attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:1 constant:0];  NSLayoutConstraint *heightConstraint= [NSLayoutConstraint constraintWithItem:v attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeHeight multiplier:1 constant:0];      [v addConstraints:@[widthConstraint , heightConstraint]];

以上代碼運行結果:

[LayoutConstraints] The view hierarchy is not PRepared for the constraint: <NSLayoutConstraint:0x6100000859b0 UIView:0x7f81c8d0ac50.width == UIView:0x7f81c8e08240.width   (inactive)>When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView(UIConstraintBasedLayout) _viewHierarchyUnpreparedForConstraint:] to debug. [LayoutConstraints] View hierarchy unprepared for constraint.Constraint: <NSLayoutConstraint:0x6100000859b0 UIView:0x7f81c8d0ac50.width == UIView:0x7f81c8e08240.width   (active)>Container hierarchy: <UIView: 0x7f81c8d0ac50; frame = (0 0; 0 0); layer = <CALayer: 0x610000038b40>>View not found in container hierarchy: <UIView: 0x7f81c8e08240; frame = (0 0; 414 736); autoresize = W+H; layer = <CALayer: 0x600000037c80>>

That view's superview: NO SUPERVIEW

解決方法是:  NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:v attribute:NSLayoutAttributeWidth multiplier:1 constant:0];  NSLayoutConstraint *heightConstraint= [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:v attribute:NSLayoutAttributeHeight multiplier:1 constant:0];      [self.view addConstraints:@[widthConstraint , heightConstraint]];原理是:在viewDidLoad方法中,view的層級并沒有裝載完成,這個方法只是將所有UIView的實例加載到內存中,而沒有完成層級的組裝,這個時候,針對自定義的UIView子類的實例使用LayoutConstraint,參照對象是self.view, 就會產生Crash。但是,系統在self.view被顯示出來之前,會完成self.view的裝載,那么,self.view就是固定的,我們可以依據NSLayoutConstraint類提供的公式view1.attr1 <relation> multiplier × view2.attr2 + c進行反推。也就是解決辦法中的用法為什么可以解決問題的原因.

關于公式,請參照:iOS 布局匯總


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 元谋县| 理塘县| 铜川市| 辽阳县| 津南区| 张家界市| 库尔勒市| 黄平县| 曲阳县| 皋兰县| 凤阳县| 高陵县| 甘孜县| 台江县| 越西县| 确山县| 海安县| 金昌市| 武穴市| 勃利县| 南汇区| 广河县| 涡阳县| 澄江县| 霍林郭勒市| 万安县| 台江县| 同仁县| 密山市| 资溪县| 泰兴市| 黎川县| 灵丘县| 海宁市| 土默特左旗| 铜鼓县| 成都市| 右玉县| 凤城市| 满城县| 石城县|