怎么在一行上同时显示多个 button,每个 button 的 frame 由 button 的 title 文字个数确定,且每个 button 的间距是一样的呢?
上代码:
NSArray *arr = @[@"好了知道了",@"切切切",@"这样真的",@"嗷嗷嗷",@"熊抱",@"思密达",@"知道了",@"沫沫酱紫",@"天蝎座",@"一直喜欢你",@"暴走大事件",@"哔哩哔哩",@"索尼大法好"];
CGFloat w = 0;//保存前一个button的宽以及前一个button距离屏幕边缘的距离
CGFloat h = 200;//用来控制button距离父视图的高
for (int i = 0; i < arr.count; i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];//此处必须为 system 如果为custom 字体大小将永远是17,无法完全显示文字
button.tag = 100 + i;
UIImage *image = [UIImage imageNamed:@"4"];
//image根据文字的多少进行拉伸
UIImage *newImage = [image stretchableImageWithLeftCapWidth:.2 topCapHeight:.5];
[button setBackgroundImage:newImage forState:UIControlStateNormal];
[button addTarget:self action:@selector(handleClick:) forControlEvents:UIControlEventTouchUpInside];
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//根据计算文字的大小
CGFloat length = [arr[i] boundingRectWithSize:CGSizeMake(self.view.frame.size.width, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]} context:nil].size.width;
//为button赋值
[button setTitle:arr[i] forState:UIControlStateNormal];
//设置button的frame
button.frame = CGRectMake(10 + w, h, length + 15 , 30);
//当button的位置超出屏幕边缘时换行 只是button所在父视图的宽度
if(10 + w + length + 15 > self.view.frame.size.width){
w = 0; //换行时将w置为0
h = h + button.frame.size.height + 10;//距离父视图也变化
button.frame = CGRectMake(10 + w, h, length + 15, 30);//重设button的frame
}
w = button.frame.size.width + button.frame.origin.x;
[self.view addSubview:button];
}
//点击事件
- (void)handleClick:(UIButton *)btn{
NSLog(@"%@",btn.titleLabel.text);}
效果图: