国产探花免费观看_亚洲丰满少妇自慰呻吟_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 布局匯總


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 嘉禾县| 宜阳县| 临西县| 武山县| 正镶白旗| 黔江区| 株洲市| 青冈县| 兴城市| 许昌县| 韩城市| 张家界市| 商都县| 扶风县| 陵水| 乾安县| 九龙县| 溧阳市| 清流县| 通化县| 友谊县| 张家川| 太仓市| 上犹县| 锡林郭勒盟| 通山县| 西乌珠穆沁旗| 博客| 志丹县| 芦溪县| 张掖市| 麻城市| 左云县| 无极县| 靖州| 衡南县| 扶余县| 大港区| 文昌市| 潜江市| 南雄市|