CGFloat height = self.scrollView.bounds.size.height;
CGFloat btnX = 5;
for (int index = 0; index < dataSource.count; index ++) {
UIButton *button = [[UIButton alloc] init];
[self.scrollView addSubview:button];
[button setTitleColor:[UIColor darkTextColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
button.titleLabel.font = [UIFont systemFontOfSize:16];
NSString *title = dataSource[index];
[button setTitle:title forState:UIControlStateNormal];
//计算宽
CGSize titleSize = [title sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:button.titleLabel.font.fontName size:button.titleLabel.font.pointSize]}];
CGFloat width = titleSize.width+10;
button.frame = CGRectMake(btnX, 0, width, height);
[button addTarget:self action:@selector(categoriesBtnAction:) forControlEvents:UIControlEventTouchUpInside];
btnX += button.frame.size.width;
}
self.scrollView.contentSize = CGSizeMake(btnX, height);
根据文本内容调整Button大小
最新推荐文章于 2021-02-21 13:12:09 发布
本文介绍了一种使用Swift在iOS应用中动态创建并布局按钮的方法。通过遍历数据源,在UIScrollView中添加UIButton,并根据按钮标题自动调整宽度和位置,实现水平布局效果。
部署运行你感兴趣的模型镜像
您可能感兴趣的与本文相关的镜像
Python3.10
Conda
Python
Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本
317

被折叠的 条评论
为什么被折叠?



