简体   繁体   English

IBOutlet UIImageView

[英]IBOutlet UIImageView

I got 30 of these codes, with the same implementation: 我得到了其中的30个代码,并且实现相同:

// .h // 。H

@interface ViewController : UIViewController{
IBOutlet UIImageView *circle;
IBOutlet UIImageView *circle2;
}
@property (nonatomic, retain) IBOutlet UIImageView *circle;
@property (nonatomic, retain) IBOutlet UIImageView *circle2;

// .m // .m

@implementation ViewController

@synthesize circle;
@synthesize circle2;

- (void)viewDidLoad
{
circle = [[UIImageView alloc]
                      initWithImage:[UIImage imageNamed:@"Circle.png"]];
circle2 = [[UIImageView alloc]
                      initWithImage:[UIImage imageNamed:@"Circle.png"]];
}

And somewhere in my code, Im adding it as a subview. 在我代码的某个位置,我将其添加为子视图。

My problem is,Is there a way to make it shorter, for it to be maintainable. 我的问题是,有没有一种方法可以缩短它,使其易于维护。

If you use name like - Circle1.png , Circle2.png , then you can go for for loop for creating this in a loop. 如果使用类似Circle1.pngCircle2.png名称,则可以使用for循环在循环中创建它。

Something like - 就像是 -

for (int i = 0; i < imageCount ; i++ ) {
    circle = [[UIImageView alloc]
                  initWithImage:[UIImage imageNamed:[NSString stringWithFormat: @"Circle%d.png" , i]]];
}

Is there a pattern to where you are putting these views in their superview? 您是否将这些视图置于其超级视图中? If so, you could use a for loop that goes to 30 and programmatically create the views and add them to their superview. 如果是这样,您可以使用一个for循环,该循环转到30,并以编程方式创建视图并将其添加到其超级视图。

So for example: 因此,例如:

   for (i = 0; i < 100; i++)
    {
        UIImageView* circle = [[UIImageView alloc]
                      initWithImage:[UIImage imageNamed:@"Circle.png"]];
        [self.view addSubview:circle];
    }

Would add 100 of the image views you would want. 将添加您想要的100个图像视图。 Of course you will need to adjust the positions of each of these views in the loop, but this is the general idea. 当然,您将需要在循环中调整这些视图中每个视图的位置,但这是一般的想法。

You can use one IBOutletCollection instead of 30 IBOutlets . 您可以使用一个IBOutletCollection而不是30个IBOutlets You probably want to set the tag on each UIImageView though, so you can still tell them apart. 不过,您可能想在每个UIImageView上设置标签,因此仍然可以区分它们。

(This answer assumes you use a nib. Remove the lines where you instantiate the UIImageView s in viewDidLoad if so.) (此答案假设您使用的是笔尖。如果是这样,请删除在viewDidLoad实例化UIImageView的行。)

创建此ViewController时,将框架作为参数传递。那是唯一更改rite ??的事情。图像是相同的,并且没有其他属性..它可能起作用

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

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