我在 Xcode 6 中做一个自动布局的项目,我以编程方式添加标签,它在 4s、5、5s 中完美工作,但在 6 和 6 plus 中不起作用。谁能帮助我,我是自动布局的新手。下面是我的编码。
UIScrollView *scroll = [[UIScrollView alloc]init];
[scroll setTranslatesAutoresizingMaskIntoConstraints:NO];
scroll.contentSize=CGSizeMake(480, 600);
[centerView addSubview:scroll];
NSDictionary *scrolldic = @{@"scrollview":scroll};
NSArray *scroll_H = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[scrollview(480)]" options:0 metrics:Nil views:scrolldic];
NSArray *scroll_V = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[scrollview(480)]" options:0 metrics:Nil views:scrolldic];
[scroll addConstraints:scroll_H];
[scroll addConstraints:scroll_V];
NSArray *scroll_posH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[scrollview]" options:0 metrics:Nil views:scrolldic];
NSArray *scroll_posV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[scrollview]" options:0 metrics:Nil views:scrolldic];
[self.view addConstraints:scroll_posH];
[self.view addConstraints:scroll_posV];
UILabel *header = [[UILabel alloc]init];
[header setTranslatesAutoresizingMaskIntoConstraints:NO];
header.backgroundColor = [UIColor blueColor];
[scroll addSubview:header];
NSDictionary *headerdic = @{@"header":header};
NSArray *header_H = [NSLayoutConstraint constraintsWithVisualFormat:@"H:[header(150)]" options:0 metrics:Nil views:headerdic];
NSArray *header_V = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[header(30)]" options:0 metrics:Nil views:headerdic];
[header addConstraints:header_H];
[header addConstraints:header_V];
NSArray *header_posH = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-80-[header]" options:0 metrics:Nil views:headerdic];
NSArray *header_posV = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[header]" options:0 metrics:Nil views:headerdic];
[self.view addConstraints:header_posH];
[self.view addConstraints:header_posV];
看上图4s标签在中间是正确的,但是在6中它向左移动了一些,有什么问题可以帮助我吗?
最佳答案
要让它发挥作用,您希望布局在不同设备上的外观也很重要。标签应该始终具有 150 的宽度并居中,还是应该始终具有 80 的左右填充?
这是你必须决定的,但约束看起来像这样:
第一种情况(宽度相同且居中):
NSLayoutConstraint *centerXConstraint = [NSLayoutConstraint constraintWithItem:header attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem: scroll attribute:NSLayoutAttributeCenterX multiplier:1.f constant:0];
[scroll addConstraint:centerXConstraint];
第二种情况(保持设备之间的填充):
[scroll addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-leftPadding-[header]-leftPadding-|" options:0 metrics:@{ @"leftPadding": @(80) } views:@{ @"header": header }]];
如果您需要更多帮助,请告诉我。
关于ios - 如何在自动布局中以编程方式执行 uilabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29675973/