商品选择控件

2017-04-25  本文已影响25人  sherlock_m

在项目中写这个控件的时候,细节还是很多的,比如如何根据后台传过来的json来布局里面的子控件。

1.先来看看效果图

DB931AEF-935F-426E-95D5-5D3D402EC88F.png

2.看下控件的视图层级

05EFFA2C-3A44-4811-A765-9E6863E471F3.png

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;

'''

上一篇下一篇

猜你喜欢

热点阅读