Button宽度自定义

-(void)setreMenUI{
    
    remenView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, CurrentWidth, CurrentHeight-64)];
    remenView.backgroundColor = [UIColor whiteColor];
    remenView.userInteractionEnabled = YES;
    [self.view addSubview:remenView];
    
    
    
    //================
    
    UIImageView *shuimg= [[UIImageView alloc]initWithFrame:CGRectMake(15, 17, 3, 20)];
    shuimg.backgroundColor = [UIColor greenColor];
    [remenView addSubview:shuimg];
    
    UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(shuimg.frame)+10, CGRectGetMinY(shuimg.frame), 200, 20)];
    lab.text = @"热门搜索";
    lab.textColor = [UIColor grayColor];
    lab.font = [UIFont systemFontOfSize:13];
    [remenView addSubview:lab];
    
    NSArray *tarr = @[@"盗墓笔记",@"空空道人谈股市",@"叶文有话要说",@"相声",@"二货一箩筐",@"单田方",@"城市",@"美女",@"社交恐惧",@"家庭矛盾",@"失恋",@"局势很简单",@"Word",@"美女",@"美女与野兽",@"体育",@"生化危机"];
    
    float butX = 15;
    float butY = CGRectGetMaxY(shuimg.frame)+10;
    for(int i = 0; i < tarr.count; i++){
        
        //宽度自适应
        NSDictionary *fontDict = @{NSFontAttributeName:[UIFont systemFontOfSize:13]};
        CGRect frame_W = [tarr[i] boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:fontDict context:nil];
        
        if (butX+frame_W.size.width+20>CurrentWidth-15) {
            
            butX = 15;
            
            butY += 55;
        }
        
        UIButton *but = [[UIButton alloc]initWithFrame:CGRectMake(butX, butY, frame_W.size.width+20, 40)];
        [but setTitle:tarr[i] forState:UIControlStateNormal];
        [but setTitleColor:[UIColor darkTextColor] forState:UIControlStateNormal];
        but.titleLabel.font = [UIFont systemFontOfSize:13];
        but.layer.cornerRadius = 8;
        but.layer.borderColor = [UIColor lightGrayColor].CGColor;
        but.layer.borderWidth = 1;
        but.tag = 1000 + i;
        [remenView addSubview:but];
        
        butX = CGRectGetMaxX(but.frame)+10;
        
        [but addTarget:self action:@selector(btnAct:) forControlEvents:UIControlEventTouchUpInside];
    }
    
}
//直接将btn的title传到下一页放到接口中请求数据;
- (void)btnAct:(UIButton *)btn
{
    
    FirstViewController *firstVc = [[FirstViewController alloc]init];
    
        firstVc.titleHHHH = [btn currentTitle];

    [self.navigationController pushViewController:firstVc animated:YES];
}
原文地址:https://www.cnblogs.com/LzwBlog/p/6635556.html