简体   繁体   English

设置多个UIImageView实例

[英]Setting up multiple UIImageView instances

I would like to create a 4 x 6 grid of UIImageViews that each contain a slightly different image. 我想创建一个UIImageViews的4 x 6网格,每个网格包含一个略有不同的图像。 I would also like to be able to randomly select one of the instances and change it's image. 我还希望能够随机选择一个实例并更改其图像。

My question is what's the best way to set up the UIImageViews in a grid formation, perform a few actions between each setup, and randomly pick 1 of the 24 instances once setup is complete. 我的问题是以网格形式设置UIImageViews,在每个设置之间执行一些操作以及在设置完成后随机选择24个实例中的1个的最佳方法是什么。 Optimally, I wouldn't have to set up each one by one. 理想情况下,我不必一一设置。

Thanks in advance. 提前致谢。

There are different approaches you can take, depending on whether or not you want to use Interface Builder to layout your grid. 可以采用不同的方法,具体取决于您是否要使用Interface Builder来布局网格。

One option is to layout your 24 UIImageViews as subviews of a common parent view within IB. 一种选择是将24个UIImageViews布局为IB中公共父视图的子视图。 On the View Attributes tab you can set a "Tag" number from 1 to 24 to differentiate your UIImageViews. 在“视图属性”选项卡上,可以将“标记”数字设置为1到24,以区分UIImageViews。 Then in your code you can use [parentView viewWithTag:tagNumber] to access each UIImageView. 然后,在您的代码中可以使用[parentView viewWithTag:tagNumber]访问每个UIImageView。

If you prefer to do things more programmatically, you could create each of your UIImageViews in a loop in the loadView method of your UIViewController subclass. 如果您希望以编程方式做更多的事情,则可以在UIViewController子类的loadView方法中循环创建每个UIImageViews。 You could maintain an array (or an array of arrays corresponding to rows and columns) as a property of your controller, and store a reference to each of these image views as you create them. 您可以将一个数组(或与行和列对应的数组数组)作为控制器的属性,并在创建它们时存储对每个图像视图的引用。 For each UIImageView you create, set its imageView.frame property to define its position, then call [view addSubview:imageView] to add it to the parent view. 对于您创建的每个UIImageView,设置其imageView.frame属性以定义其位置,然后调用[view addSubview:imageView]将其添加到父视图。

I would do it programmatically for your sake. 我会以编程方式为您着想。

NSArray *myViews = //I assume you can create an array of views

for (int i=0; i<rows; ++i) {
    for (int j=0; j<columns; ++j) {
        UIImageView *thisImageView = [myViews objectAtIndex:(i*columns+j)];
        CGSize size = thisImageView.image.size;
        [thisImageView setFrame:CGRectMake(j*size.width, i*size.height, size.width, size.height)];
        [self.view addSubview:thisImageView];
    }
}

//Later to pick one randomly
UIImageView *myRandomView = [myViews objectAtIndex:(arc4random()%[myViews count])];
[myRandomView setImage:myNewImage];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM