masonry布局,纯代码与xib结合,在自定义cell中,for循环动态创建imageView,并且自适应cell的高度。
自适应高度
放眼如今的UI界面设计,可以发现没有任何一个APP可以固定高度,包括文字的换行,图片的数量不确定的种种因素,对于自适应高度已经是基本的要求。
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 100;
}
- 实现方法也很简单基本就是依靠,预估一个高度,系统自动自己算。
如果需要这句代码起作用的关键就是 :需要让你的cell内部视图充满你的contentView,也就是内部视图相互关联能够距离顶部,和底部的相关约束才行。这样通过视图把整个cell撑起来,让cell有应该属于自己的合适的高度。
优先级 priority
if (i == self.imgeArray.count -1) {
make.bottom.equalTo(imageView.superview).offset(0).priorityLow();
}
- 优先级(1000),即优先满足,必须满足的约束条件。
- 优先级(<1000),即满足了必须满足的条件,条件允许的情况下,次要满足的条件
- 一个控件(一个view视图),通过top,left,right,以及高度4个约束,已经能够确定他的位置,如果此时想要把cell的contentView充满就要增加底部bottom约束,此时就会出现约束冲突。解决办法就是优先级,设置priorityLow给优先级低的约束。
masonry布局,纯代码与xib结合,在自定义cell中,for循环动态创建imageView
@property (weak, nonatomic) IBOutlet UIView *customImagesView;
- IBOutlet 通过将xib中的控件(甚至是约束条件)拖到代码里进行进一步加工。
- customImagesView需要满足的条件就是,关联控件的内部约束,是符合撑满contentView的所属控件即可。
- (void)setImgeArray:(NSArray *)imgeArray {
_imgeArray = imgeArray;
CGFloat height = 105;
CGFloat margin = 14;
CGFloat customImagesViewLeft = 107;
// CGFloat width = 158;
CGFloat width = (k_SCREEN_WIDTH - customImagesViewLeft - margin * 2) * 0.5;
for (UIView * subView in self.customImagesView.subviews) {
[subView removeFromSuperview];
}
for (int i = 0; i<self.imgeArray.count; i++) {
UIImageView * imageView = [[UIImageView alloc] init];
[imageView setContentMode:UIViewContentModeScaleAspectFill];
[self.customImagesView addSubview:imageView];
imageView.backgroundColor = [UIColor colorWithRandom];
[imageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(imageView.superview).offset(height * (i / 2) + margin * (i / 2));
make.left.equalTo(imageView.superview).offset(width *(i % 2) + margin * (i % 2));
make.width.offset(width);
make.height.offset(height);
if (i == self.imgeArray.count -1) {
make.bottom.equalTo(imageView.superview).offset(0).priorityLow();
}
}];
}
}
- 通过setter方法拿到接口数据,进行动态创建视图,刷新tableView如此就可以根据显示的内容适应高度
WX20220123-141018@2x.png WX20220123-141106@2x.png WechatIMG4.jpeg
网友评论