一开始,这里是 screenshot of my ViewController in Action .
我的 ViewController
包含嵌入式 YouTube 视频,下面是 UIScrollView
,下面是 UITableView
,目前是随机填充的。我想获取特定歌手的所有专辑,并且对于每个专辑,都有一个单独的 UIButton
如屏幕截图 ->
svi, lek za spavanje, balkan
问题是,我将从 YouTube API
获取所有专辑,所以我不知道歌手有多少张专辑。我必须在 Swift 中以编程方式添加 UIButton。
在我的语言中,“svi”的意思是“全部”,所以当我单击“svi”时,我应该在 UITableView
中看到它下面列出的所有相册。同样,所有相册和“svi”(“all”) 都应该在 UIScrollView
中,因此当用户单击时,例如“Balkan”,应该填充 UITableView
包含该“Balkan”专辑中的所有轨道。
谁能建议我如何根据提供的屏幕截图在 UIScrollView
中制作和定位所有 UIButtons
(作为 UIButtons 的数组
)在顶部?任何帮助表示赞赏。
最佳答案
- 在 Storyboard中添加 ScrollView /以编程方式添加
- 有一个包含专辑列表的数组
- 以编程方式创建
UIButton
并将其添加到 ScrollView - 最后设置 ScrollView 的大小。
代码片段如下,
UIScrollView * scView;
UIButton * btn;
NSMutableArray * array;
float btnWidth = 44;
for(int i=0;i<array.count;i++) {
btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(i*btnWidth, 0, btnWidth, 44);
[btn setTitle:[array objectAtIndex:i]forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btnTapped) forControlEvents:UIControlEventTouchUpInside];
[scView addSubview:btn];
}
[scView setContentSize:CGSizeMake(btnWidth*array.count, 50)];
- (void)btnTapped {
// button click call back method
}
用下面的方法检查字符串的大小
- (CGSize)getHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font {
CGSize size = CGSizeZero;
if (text) {
CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName:font } context:nil];
size = CGSizeMake(frame.size.width, frame.size.height);
}
return size;
}
将您的相册名称传递给此方法,它返回 CGSize
,从中获取宽度并将该宽度值设置为上面 for 循环中的按钮宽度。
关于ios - 在 UIScrollView 中添加和定位 UIButtons 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34810716/