我有一个包含 200 多个项目的大型数组。每个项目都有与之关联的图像。每个图像都必须能够被点击。我将它们全部作为 UIButtons 添加到 UIScrollView。对于循环,我有以下代码:
for (NSString *item in items) {
UIButton *button = [[UIButton alloc] initWithFrame:(CGRectMake(xValue, 0, 70, 70))];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[button setTag:(xValue/75)];
[button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@.png",item]] forState:UIControlStateNormal];
xValue += 75;
[scrollView addSubview:button];
}
这确实添加了按钮,但我希望它们在添加时显示在 View 中。或者,如果有可能在 View 加载之前预加载按钮,那就太好了。
最佳答案
您不想以这种方式构建它。您应该改为使用水平 UICollectionView
。
如果您这样做,您会将每个图像都加载到内存中,这可能会出现问题。通过使用 Collection View , Collection View 将只加载在给定时间需要在屏幕上呈现的单元格数量,从而减少应用程序的内存占用。它还会适本地设置 Collection View 的内容大小。
关于ios - 如何使用 for 循环将多个 UIButton 实时添加到 UIScrollView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50205181/