【问题标题】:Why I will get this wrong when I add some constraints in subView?为什么我在 subView 中添加一些约束时会出错?
【发布时间】:2018-03-09 02:49:11
【问题描述】:

LogoView 是 top_bg 的子视图。 top_bg 是窗口的子视图。我尝试使用 LogoView 添加约束。为什么我会弄错这些?

 CGRect screenFrame = [[UIScreen mainScreen] bounds];
 UIImageView *logoView = [[UIImageView alloc]init];//logo
UIImage *logoImage = [UIImage imageNamed:@"top_ico.png"];
[logoView setImage:logoImage];//below add constraint
//  logoView.frame = CGRectMake(150.0f,0.0f, 304.74f, 60.0f);
[logoView setTranslatesAutoresizingMaskIntoConstraints:NO];
NSLayoutConstraint *logoConstraint_0 = [NSLayoutConstraint constraintWithItem:logoView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:top_bg attribute:NSLayoutAttributeTop multiplier:1.0f constant:0.0f];
NSLayoutConstraint *logoConstraint_1 = [NSLayoutConstraint constraintWithItem:logoView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:top_bg attribute:NSLayoutAttributeLeft multiplier:1.0f constant:screenFrame.size.width/2.0f];
NSLayoutConstraint *logoConstraint_2 = [NSLayoutConstraint constraintWithItem:logoView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:304.74f];
NSLayoutConstraint *logoConstraint_3 = [NSLayoutConstraint constraintWithItem:logoView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:60.0f];
NSArray *LogoConstraints = [NSArray arrayWithObjects:logoConstraint_0,logoConstraint_1,logoConstraint_2,logoConstraint_3,nil];
[top_bg addConstraints:LogoConstraints];
[top_bg addSubview:logoView];

下面是我运行时的错误。

2018-03-09 10:43:54.114041+0800 MainUI[1855:81910] [LayoutConstraints] 视图层次结构没有为约束准备:<0x60000009b080 uiimageview:0x7f9196429a20.top="=" uiimageview:0x7f9196615d70.>

标签: ios objective-c constraints


【解决方案1】:

我得到了答案!,就像下面的代码

-(instancetype) initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        self.top_bg = [[UIImageView alloc]init];
        self.logoView=[[UIImageView alloc]init];
        [self.top_bg addSubview:self.logoView];
    }
    return self;
}

在添加一些约束之前,我必须确认 View 的层次结构!我无法添加约束然后 addSubViews。

【讨论】:

    【解决方案2】:

    您需要更改代码顺序,即首先将 logoView 添加为子视图,然后添加其约束。

    先添加子视图

    [top_bg addSubview:logoView];
    

    以及应用约束

    NSArray *LogoConstraints = [NSArray arrayWithObjects:logoConstraint_0,logoConstraint_1,logoConstraint_2,logoConstraint_3,nil];
    [top_bg addConstraints:LogoConstraints];
    

    【讨论】:

      猜你喜欢
      • 2018-05-21
      • 1970-01-01
      • 2022-11-14
      • 2021-01-20
      • 1970-01-01
      • 2019-07-13
      • 1970-01-01
      • 2020-01-24
      • 1970-01-01
      相关资源
      最近更新 更多