我必须在自定义的 UITableViewCell 中以编程方式添加一些约束,我有一个 mainView(红色),它将是一个容器(cell.contentView 的子视图)、一个图像和 mainView 的其他 2 个子视图。
这就是我想要的(蓝色和黄色视图的高度不同,但这是另一个问题):
使用下面的代码(我还没有添加 imageView),我有这个:
如您所见,两个子视图具有相同的大小,当我滚动时,有时会显示蓝色视图,有时会显示黄色视图。
代码 :
self.mainView = [[UIView alloc]init];
[self.mainView setBackgroundColor:[UIColor redColor]];
[self.mainView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.contentView addSubview:self.mainView];
UIView *blueView = [[UIView alloc]init];
[blueView setTranslatesAutoresizingMaskIntoConstraints:NO];
[blueView setBackgroundColor:[UIColor blueColor]];
[self.mainView addSubview:blueView];
UIView *yelloView = [[UIView alloc]init];
[yelloView setBackgroundColor:[UIColor yellowColor]];
[yelloView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.mainView addSubview:yelloView];
NSDictionary *views = NSDictionaryOfVariableBindings(blueView,yelloView,mainView);
NSMutableArray *results = [NSMutableArray array];
NSString *mainContentView_CVF_H = @"H:|-[blueView]-|";
NSString *mainContentView_CVF_V = @"V:|-[blueView]";
NSArray *mainContentViewConstaints_H = [NSLayoutConstraint constraintsWithVisualFormat:mainContentView_CVF_H options:0 metrics:nil views:views];
NSArray *mainContentViewConstaints_V = [NSLayoutConstraint constraintsWithVisualFormat:mainContentView_CVF_V options:0 metrics:nil views:views];
[results addObjectsFromArray:mainContentViewConstaints_H];
[results addObjectsFromArray:mainContentViewConstaints_V];
NSString *delivelyView_CVF_H = @"H:|-[yelloView]-|";
NSString *delivelyView_CVF_V = @"V:[blueView][yelloView]-|";
NSArray *delivelyViewConstaints_H = [NSLayoutConstraint constraintsWithVisualFormat:delivelyView_CVF_H options:0 metrics:nil views:views];
NSArray *delivelyViewConstaints_V = [NSLayoutConstraint constraintsWithVisualFormat:delivelyView_CVF_V options:0 metrics:nil views:views];
[results addObjectsFromArray:delivelyViewConstaints_H];
[results addObjectsFromArray:delivelyViewConstaints_V];
[self.mainView addConstraints:results];
NSString *mainView_CVF_H = @"H:|-[mainView]-|";
NSString *mainView_CVF_V = @"V:|-[mainView]-|";
results = [NSMutableArray array];
NSArray *mainViewConstaints_H = [NSLayoutConstraint constraintsWithVisualFormat:mainView_CVF_H options:0 metrics:nil views:views];
NSArray *mainViewConstaints_V = [NSLayoutConstraint constraintsWithVisualFormat:mainView_CVF_V options:0 metrics:nil views:views];
[results addObjectsFromArray:mainViewConstaints_H];
[results addObjectsFromArray:mainViewConstaints_V];
[self.contentView addConstraints:results];
我用 2 个文本文件替换子视图(蓝色和黄色),没有任何修改,它们按预期显示。
2个问题:
你能帮我吗 :) ?
添加约束的顺序很重要吗?