標(biāo)簽的大小根據(jù)上面的文字來自適應(yīng)大小,需要根據(jù)后臺返回的數(shù)據(jù)自動換行.沒有添加
NSArray *arr = @[@"無知",@"風(fēng)云變幻",@"施耐庵",@"唉",@"西門吹雪",@"呵呵噠",@"快看看",@"窿窿啦啦",@"一桿禽獸狙",@"合歡花",@"暴走大事件",@"非誠勿擾",@"呵呵呵"];
CGFloat w = 0;//保存前一個button的寬以及前一個button距離屏幕邊緣的距離
CGFloat h = 200;//用來控制button距離父視圖的高
for (int i = 0; i < arr.count; i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.tag = 100 + i;
button.backgroundColor = [UIColor greenColor];
[button addTarget:self action:@selector(handleClick:) forControlEvents:UIControlEventTouchUpInside];
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//根據(jù)計算文字的大小
NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
CGFloat length = [arr[i] boundingRectWithSize:CGSizeMake(320, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
//為button賦值
[button setTitle:arr[i] forState:UIControlStateNormal];
//設(shè)置button的frame
button.frame = CGRectMake(10 + w, h, length + 15 , 30);
//當(dāng)button的位置超出屏幕邊緣時換行 320 只是button所在父視圖的寬度
if(10 + w + length + 15 > 320){
w = 0; //換行時將w置為0
h = h + button.frame.size.height + 10;//距離父視圖也變化
button.frame = CGRectMake(10 + w, h, length + 15, 30);//重設(shè)button的frame
}
w = button.frame.size.width + button.frame.origin.x;
[self.view addSubview:button];
}
點擊事件
- (void)handleClick:(UIButton *)btn{
NSLog(@"%ld",btn.tag);
}
原文地址>http://blog.csdn.net/duoduo_333/article/details/47024551#