效果如图:
居中.gif
前言
需求是只有一个,两个,三个item
的时候居中,超过限制宽度的时候做成从左往右的滚动效果。
分析
要求居中,所以我们给一个大的容器,让其居中即可,高度确定,宽度根据子视图自适应,因此可以考虑用UIScrollview
的自适应。
[self.scrollView1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.height.mas_equalTo(FixH(59));
make.centerX.mas_equalTo(0);
make.top.mas_equalTo(SafeAreaTopHeight);
}];
代码
用UIScrollview
做容器
-(instancetype)init{
self = [super init];
if (self) {
UIScrollView *scrollView = UIScrollView.new;
self.scrollView = scrollView;
self.scrollView.showsVerticalScrollIndicator = NO;
self.scrollView.showsHorizontalScrollIndicator = NO;
scrollView.backgroundColor = [UIColor whiteColor];
[self addSubview:scrollView];
[self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self);
}];
self.count = 5;
}
return self;
}
UIScrollView
的宽度自适应需要一个容器,Masonry
的GitHub
示例中高度自适应也是如此。
- (void)generateContent {
[self.contentView removeFromSuperview];
//scrollView 需要一个撑满的容器
UIView* contentView = UIView.new;
[self.scrollView addSubview:contentView];
[contentView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(self.scrollView);
make.height.equalTo(self.scrollView);
}];
self.contentView = contentView;
LXScrollViewItem *lastButton = nil;
CGFloat totalWidth = FixW(30);
CGFloat space = FixW(30);
for (int i = 0; i < self.count; i++) {
LXScrollViewItem *view = [[LXScrollViewItem alloc]init];
view.backgroundColor = [UIColor whiteColor];
[_contentView addSubview:view];
view.icon.image = [UIImage imageNamed:@"头像"];
NSString *str = @"忒修斯";
view.textLabel.text = str;
//计算宽度
CGFloat width = [str sizeWithFont:[UIFont systemFontOfSize:11 weight:UIFontWeightMedium] maxSize:CGSizeMake(CGFLOAT_MAX, FixH(13))].width;
if (width <= FixW(32)) {
width = FixW(32);
}
[view mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.mas_equalTo(0);
if (!lastButton) {
make.left.mas_equalTo(space);
}else{
make.left.mas_equalTo(lastButton.mas_right).offset(space);
}
make.width.mas_equalTo(width);
make.height.equalTo(self.contentView);
}];
totalWidth += (width + space);
lastButton = view;
}
//容器右侧根据子视图确定
[self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
make.right.mas_equalTo(lastButton.mas_right).offset(space);
}];
//限制滚动,设置内容区域
if (totalWidth >= kScreenWidth - space) {
self.scrollView.scrollEnabled = YES;
[self mas_updateConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(kScreenWidth - space);
}];
}else{
self.scrollView.scrollEnabled = NO;
[self mas_updateConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(totalWidth);
}];
}
}
demo地址:居中自适应布局