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


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 灌阳县| 桃园县| 剑川县| 营口市| 瑞金市| 沧州市| 普宁市| 永兴县| 天津市| 蒲城县| 澎湖县| 余姚市| 卫辉市| 喜德县| 尼木县| 德昌县| 岳阳县| 博爱县| 宾阳县| 灵台县| 贵州省| 阳朔县| 乳源| 莲花县| 九江市| 渭源县| 肇源县| 佛冈县| 天峨县| 凤城市| 汉川市| 上蔡县| 怀宁县| 丰城市| 台州市| 景宁| 泗水县| 军事| 新昌县| 图木舒克市| 正宁县|