iOS,搜索标签布局

释放双眼,带上耳机,听听看~!

//  代码地址: https://github.com/iphone5solo/PYSearch

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**  添加和布局标签 */
- (NSArray *)addAndLayoutTagsWithTagsContentView:(UIView *)contentView tagTexts:(NSArray<NSString *> *)tagTexts;
{
    // 清空标签容器的子控件
    [contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    // 添加热门搜索标签
    NSMutableArray *tagsM = [NSMutableArray array];
    for (int i = 0; i < tagTexts.count; i++) {
        UILabel *label = [self labelWithTitle:tagTexts[i]];
        [label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tagDidCLick:)]];
        [contentView addSubview:label];
        [tagsM addObject:label];
    }
    
    // 计算位置
    CGFloat currentX = 0;
    CGFloat currentY = 0;
    CGFloat countRow = 0;
    CGFloat countCol = 0;
    
    // 调整布局
    for (UILabel *subView in tagsM) {
        // 当搜索字数过多,宽度为contentView的宽度
        if (subView.py_width > contentView.py_width) subView.py_width = contentView.py_width;
        if (currentX + subView.py_width + PYMargin * countRow > contentView.py_width) { // 得换行
            subView.py_x = 0;
            subView.py_y = (currentY += subView.py_height) + PYMargin * ++countCol;
            currentX = subView.py_width;
            countRow = 1;
        else // 不换行
            subView.py_x = (currentX += subView.py_width) - subView.py_width + PYMargin * countRow;
            subView.py_y = currentY + PYMargin * countCol;
            countRow ++;
        }
    }
    // 设置contentView高度
    contentView.py_height = CGRectGetMaxY(contentView.subviews.lastObject.frame);
    // 设置头部高度
    self.baseSearchTableView.tableHeaderView.py_height = self.headerContentView.py_height = CGRectGetMaxY(contentView.frame) + PYMargin * 2;
    // 重新赋值, 注意:当操作系统为iOS 9.x系列的tableHeaderView高度设置失效,需要重新设置tableHeaderView
    [self.baseSearchTableView setTableHeaderView:self.baseSearchTableView.tableHeaderView];
    return [tagsM copy];
}<br><br><br><br>

/** 添加标签 */

– (UILabel *)labelWithTitle:(NSString *)title

{

UILabel *label = [[UILabel alloc] init];

label.userInteractionEnabled = YES;

label.font = [UIFont systemFontOfSize:12];

label.text = title;

label.textColor = [UIColor grayColor];

label.backgroundColor = [UIColor py_colorWithHexString:@”#fafafa”];

label.layer.cornerRadius = 3;

label.clipsToBounds = YES;

label.textAlignment = NSTextAlignmentCenter;

[label sizeToFit];

label.py_width += 20;

label.py_height += 14;

return label;

}

 

人已赞赏
iOS文章

iOS判断推送通知是否开启

2019-10-24 16:16:52

iOS文章

iOS 计算两个时间差 (完美)传时间字符串即可(非时间戳)

2019-10-24 17:05:48

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索