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

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

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

2019-11-09 16:42:14
字體:
來源:轉載
供稿:網友

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 布局匯總


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 滕州市| 元朗区| 澄城县| 辰溪县| 芜湖县| 宁波市| 禄丰县| 前郭尔| 陆良县| 龙里县| 城市| 达日县| 彰化市| 咸阳市| 广河县| 濉溪县| 洱源县| 西吉县| 巴塘县| 崇左市| 黎城县| 仲巴县| 鄂尔多斯市| 涿州市| 宁明县| 台北市| 泽普县| 武山县| 甘孜县| 黄陵县| 商丘市| 马山县| 日照市| 桃源县| 穆棱市| 措美县| 玉门市| 措美县| 青阳县| 焉耆| 宝鸡市|