MyLinearLayout
MyLinearLayout copied to clipboard
使用Masonry布局问题
子视图为自定义样式,使用Masonry布局,无法展示;demo代码如下:
UIView *view = [[UIView alloc] init];
view.backgroundColor = [UIColor grayColor];
UIImageView *imageView = [[UIImageView alloc] init];
imageView.backgroundColor = [UIColor redColor];
imageView.clipsToBounds = YES;
imageView.layer.cornerRadius = 8;
[view addSubview:imageView];
[imageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(view).offset(5);
make.top.greaterThanOrEqualTo(view).offset(2);
make.centerY.equalTo(view);
make.width.height.equalTo(@16);
}];
UILabel *label = [[UILabel alloc] init];
label.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5];
label.text = [NSString stringWithFormat:@" label%d ", i];
label.clipsToBounds = YES;
label.layer.cornerRadius = 8;
label.layer.borderColor = [UIColor lightGrayColor].CGColor;
label.layer.borderWidth = 0.5;
[view addSubview:label];
[label mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(imageView.mas_right).offset(5);
make.right.lessThanOrEqualTo(view).offset(-5);
make.top.greaterThanOrEqualTo(view).offset(8);
make.centerY.equalTo(view);
make.height.greaterThanOrEqualTo(@16);
}];
[self.flowLayout addSubview:view];
-(MyFlowLayout *)flowLayout {
if(_flowLayout == nil) {
_flowLayout = [MyFlowLayout flowLayoutWithOrientation:MyOrientation_Vert arrangedCount:0];
_flowLayout.subviewHSpace = 16; // 子视图之间的水平间距
_flowLayout.subviewVSpace = 8; // 子视图之间的垂直间距
_flowLayout.padding = UIEdgeInsetsMake(5, 5, 5, 5); // 视图四周的内边距值
}
return _flowLayout;
}
UIView *view = [[UIView alloc] init]; view 连尺寸都没有,也没有设置约束。
view的尺寸随内部元素大小变动,由内部视图约束撑开
MyLayout对普通视图的自适应是感觉不出来的,所以造成了你的view没有尺寸。问题是你既然已经把view当做一个容器来包装imageview和label。那么为什么不将view改为一个水平先行布局呢?代码还会少很多。
首先,感谢您的建议。但view内的样式不固定,这里只是举了个例子,例子里图片和标签是水平左右分布,但实际开发时view内的样式并不是这样. @youngsoft
因为mylayout内部是用frame来实现的,所以在布局开始时如果是非布局子视图,用的不是mylayout的约束,而是用的autolayout约束的话,可能不会生效。除非autolayout约束设置完后其中的frame计算生效才可能有效。
使用mas确实是不行,我也是尝试过用mas撑开一个包含UILabel和Image的UIView,但是展示出来怎么都是0x0的尺寸,而对view直接mas的话,又会让linearView的布局不正确,后来使用了MyLinearLayout横纵叠加的方式并整体设置:wrapContentWidth = YES; wrapContentHeight = YES;来实现布局
@aiqinxuancai 你说的“MyLinearLayout横纵叠加的方式”能详细点吗?是跟 “youngsoft” 描述的一致吗?“将view改为一个水平先行布局”
就是子view的叠加,横的MyLinearLayout里面放纵的MyLinearLayout