请看下面的代码:
- (void)viewDidLoad {
[super viewDidLoad];
UIView *view = [[UIView alloc] init];
view.translatesAutoresizingMaskIntoConstraints = NO;
NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeHeight multiplier:1.0 constant:30];
[view addConstraint:heightConstraint];
NSLog(@"view : %@", view);
}
信息打印出来:
<UIView: 0x7ae4c1b0; frame = (0 0; 0 0); layer = <CALayer: 0x7ae4e790>>
当我使用约束设置时,帧不会更改为30。为什么?如何使它工作?
答案 0 :(得分:1)
正如我在评论中所说,您需要先将视图添加到超级视图,然后在该超级视图上调用layoutIfNeeded。我不知道你为什么遇到NSLayoutAttributeNotAnAttribute有问题,它对我来说很好。
- (void)viewDidLoad {
[super viewDidLoad];
UIView *view = [[UIView alloc] init];
view.translatesAutoresizingMaskIntoConstraints = NO;
NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:30];
[view addConstraint:heightConstraint];
[self.view addSubview:view];
[self.view layoutIfNeeded];
NSLog(@"view : %@", view);
}
当我运行时,日志会给我这个结果,
2014-10-23 22:05:07.701 FrameTest[4293:1869985] view : <UIView: 0x7b724d40; frame = (0 0; 0 30); layer = <CALayer: 0x7b720760>>