ios - 如何使用 for 循环将多个 UIButton 实时添加到 UIScrollView?

标签 ios objective-c

我有一个包含 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/

相关文章:

ios - 未找到模块 'apple_sign_in'

ios - 在 Swift 中使用 Fabric - Cannonball 时应用程序崩溃?

ios - Apple 应用内订阅 : how to detect if the subscription is auto renewing?

ios - Apple Watch HealthKit - 无法识别的选择器 HKHealthStore startWorkoutSession :completion:

ios - React-native iOS,异步存储错误: "Invalid key - must be at least one character. Key: "

ios - 只运行一次代码

iphone - 如何转储存储在 Objective-C 对象(NSArray 或 NSDictionary)中的数据

objective-c - 将选定的单元格保持在大量 reloadRowsAtIndexPaths UITableView 上

iphone - iOS基于窗口的应用程序项目杀死问题

iphone - 正确填充后的空数组