OC:button自动换行

按惯例,还是先上图:

OC:button自动换行_第1张图片
效果图
#import "FYSearchHomeNoView.h"

#import "FYCustomLabel.h"
#import 

@interface FYSearchHomeNoView ()

@property(nonatomic, strong) UILabel * tipsLB;

@property(nonatomic, strong) NSArray * titleArray;

@end

@implementation FYSearchHomeNoView


- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor whiteColor];
        [self createViews];
        
    }
    return self;
}


#pragma mark - 创建视图

- (void)createViews {
    
    self.titleArray = @[@"养生壶", @"儿童羽绒服", @"列间距", @"那些年", @"儿童羽绒", @"儿童羽绒服儿童羽绒服", @"儿童羽", @"儿童羽绒", @"儿童羽绒服", @"儿童羽绒服", @"儿童羽绒服", @"儿童羽绒服", @"儿童羽绒服", @"童", @"一些面试经验的人基", @"深有体会", @"都会问", @"那些年踩过的坑", @"我的解决方案", @"许佳佳233贡献"];
    
    self.tipsLB = [FYCustomLabel FYLabelTitle:@"热搜" fontSize:FYScreenScale(34) color:@"#333333"];
    self.tipsLB.frame = CGRectMake(FYScreenScale(30), FYScreenScale(30), FYScreenScale(100), FYScreenScale(38));
    [self addSubview:self.tipsLB];
    
    CGFloat margin = FYScreenScale(30);//距边框距离
    CGFloat rolsWidth = FYScreenScale(20);//button之间列间距
    CGFloat rowsHeight = FYScreenScale(30);//button之间行间距
    CGFloat btnHeight = FYScreenScale(50);//button 的高度
    
    CGFloat positionX = 0.0;
    CGFloat positionY = CGRectGetMaxY(self.tipsLB.frame) + margin;
    
    for (int i = 0; i < self.titleArray.count; i++) {
        
        NSString * title = self.titleArray[i];
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.backgroundColor = [UIColor colorWithRed:230.0/255.0 green:230.0/255.0 blue:230.0/255.0 alpha:1.0];
        [button setTitle:title forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:FYScreenScale(30)];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        button.layer.cornerRadius = FYScreenScale(10);
        
        CGFloat btnWidth = [title boundingRectWithSize:CGSizeMake(FYSCREEN_W, btnHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil].size.width + FYScreenScale(30);
        
        if (positionX + margin + btnWidth + rolsWidth > FYSCREEN_W - margin) {
            positionX = 0.0;
            positionY += (rowsHeight + btnHeight);
        }
        
        button.frame = CGRectMake(positionX + margin, positionY, btnWidth, btnHeight);
        positionX += (margin + btnWidth);
        
        [self addSubview:button];
    }
}

- (void)buttonClick:(UIButton *)button {
    
}

@end
```

你可能感兴趣的:(OC:button自动换行)