1. 问题描述
子view有多个,宽度不一致;父view宽度需要取其最大宽度


2.代码
UIView * bgView = [[UIView alloc] init];
[self.view addSubview:bgView];
bgView.backgroundColor = [UIColor whiteColor];
view = [WPNewView new];
view.backgroundColor = [UIColor greenColor];
[bgView addSubview:view];
view2 = [WPNewView new];
view2.backgroundColor = [UIColor greenColor];
[bgView addSubview:view2];
[bgView mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerY.equalTo(self.view);
make.bottom.equalTo(view2).offset(10);
make.width.mas_lessThanOrEqualTo(400);
}];
[view mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(bgView);
make.left.equalTo(bgView).offset(10);
// make.right.equalTo(bgView).offset(-10);
make.height.mas_equalTo(50);
make.width.mas_lessThanOrEqualTo(bgView).offset(-20);
}];
[view2 mas_makeConstraints:^(MASConstraintMaker *make) {
make.height.equalTo(view);
make.left.equalTo(bgView).offset(10);
// make.right.equalTo(bgView).offset(-10);
make.top.equalTo(view.mas_bottom).offset(10);
make.width.mas_lessThanOrEqualTo(bgView);
}];
2.2 WPNewView
#import <UIKit/UIKit.h>
@interface WPNewView : UIView
@property (strong, nonatomic) UILabel *nickLabel;
@property (strong, nonatomic) UILabel *contentLabel;
@property (strong, nonatomic) UIImageView *imageView;
@end
#import "WPNewView.h"
#import "Masonry.h"
#define UIColorFromRGBA(rgbValue, alphaValue) [UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0x00FF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0x0000FF))/255.0 \
alpha:alphaValue]
#define UIColorFromRGB(rgbValue) UIColorFromRGBA(rgbValue, 1.0)
@implementation WPNewView
- (instancetype)init{
self = [super init];
if (self) {
_nickLabel = [UILabel new];
_nickLabel.font = [UIFont systemFontOfSize:14];
_nickLabel.backgroundColor = [UIColor redColor];
_nickLabel.textColor = UIColorFromRGB(0x333333);
[self addSubview:_nickLabel];
_contentLabel = [UILabel new];
_contentLabel.font = [UIFont systemFontOfSize:14];
_contentLabel.backgroundColor = [UIColor redColor];
_contentLabel.textColor = UIColorFromRGB(0x333333);
[self addSubview:_contentLabel];
_imageView = [[UIImageView alloc] init];
_imageView.backgroundColor = [UIColor redColor];
[self addSubview:_imageView];
self.nickLabel.text = @"--";
self.contentLabel.text = @"--";
[_nickLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self).offset(10);
make.top.equalTo(self).offset(6);
make.right.equalTo(self.imageView.mas_left).offset(-10);
make.height.mas_equalTo(17);
make.width.mas_lessThanOrEqualTo(300);
}];
[_contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.nickLabel);
make.top.equalTo(self.nickLabel.mas_bottom).offset(4);
make.height.mas_equalTo(13);
make.right.equalTo(self.imageView.mas_left).offset(-10);
}];
[_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.size.mas_equalTo(CGSizeMake(34, 34));
make.centerY.equalTo(self);
make.right.equalTo(self).offset(-10);
}];
}
return self;
}
@end
网友评论