在项目中写这个控件的时候,细节还是很多的,比如如何根据后台传过来的json来布局里面的子控件。
1.先来看看效果图
2.看下控件的视图层级
3.计算标签的核心代码
'''
[self.tagButtons removeAllObjects];
for (int i = 0; i< items.count; i++) {
UIButton *tagButton = [[UIButton alloc] init];
[self.tagButtons addObject:tagButton];
tagButton.backgroundColor = grayBgColor;
tagButton.layer.cornerRadius = MXMargin;
[tagButton setTitle:items[i] forState:UIControlStateNormal];
tagButton.titleLabel.font = MXFont;
// 应该要先设置文字和字体后,再进行计算
[tagButton sizeToFit];
tagButton.mx_width += 2 * MXTagMargin;
tagButton.mx_height = shopTageButtonH;
[tagButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[tagButton setTitleColor:[UIColor whiteColor] forState:UIControlStateDisabled];
[self.btnView addSubview:tagButton];
//添加点击事件
[tagButton addTarget:self action:@selector(tagButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
// 设置位置
if (i == 0) { // 最前面的标签
tagButton.mx_x = 0;
tagButton.mx_y = 0;
} else { // 其他标签
UIButton *lastTagButton = self.tagButtons[i - 1];
// 计算当前行左边的宽度
CGFloat leftWidth = CGRectGetMaxX(lastTagButton.frame) + MXTagMargin;
// 计算当前行右边的宽度
CGFloat rightWidth = self.btnView.mx_width - leftWidth;
if (rightWidth >= tagButton.mx_width) { // 按钮显示在当前行
tagButton.mx_y = lastTagButton.mx_y;
tagButton.mx_x = leftWidth;
} else { // 按钮显示在下一行
tagButton.mx_x = 0;
tagButton.mx_y = CGRectGetMaxY(lastTagButton.frame) + MXTagMargin;
}
}
}
// 最后一个标签
UIButton *lastTagButton = [self.tagButtons lastObject];
CGFloat h = CGRectGetMaxY(lastTagButton.frame);
//更新Frame
self.btnView.mx_height = h;
self.mx_height = h + 8 * MXMargin;
self.sepLineView.mx_y = self.mx_height - seprLineH;
'''