在項(xiàng)目中寫這個(gè)控件的時(shí)候,細(xì)節(jié)還是很多的,比如如何根據(jù)后臺(tái)傳過來(lái)的json來(lái)布局里面的子控件。
1.先來(lái)看看效果圖
DB931AEF-935F-426E-95D5-5D3D402EC88F.png
2.看下控件的視圖層級(jí)
05EFFA2C-3A44-4811-A765-9E6863E471F3.png
3.計(jì)算標(biāo)簽的核心代碼
'''
[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;
// 應(yīng)該要先設(shè)置文字和字體后,再進(jìn)行計(jì)算
[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];
//添加點(diǎn)擊事件
[tagButton addTarget:self action:@selector(tagButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
// 設(shè)置位置
if (i == 0) { // 最前面的標(biāo)簽
tagButton.mx_x = 0;
tagButton.mx_y = 0;
} else { // 其他標(biāo)簽
UIButton *lastTagButton = self.tagButtons[i - 1];
// 計(jì)算當(dāng)前行左邊的寬度
CGFloat leftWidth = CGRectGetMaxX(lastTagButton.frame) + MXTagMargin;
// 計(jì)算當(dāng)前行右邊的寬度
CGFloat rightWidth = self.btnView.mx_width - leftWidth;
if (rightWidth >= tagButton.mx_width) { // 按鈕顯示在當(dāng)前行
tagButton.mx_y = lastTagButton.mx_y;
tagButton.mx_x = leftWidth;
} else { // 按鈕顯示在下一行
tagButton.mx_x = 0;
tagButton.mx_y = CGRectGetMaxY(lastTagButton.frame) + MXTagMargin;
}
}
}
// 最后一個(gè)標(biāo)簽
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;
'''