0

我想用不同的标签以编程方式创建多个UIImageView,并将它们添加为我的主视图的子视图。以编程方式创建多个UIImageViews

我在报头中的我的UIImageView的财产:

@property (strong, nonatomic) UIImageView *grassImage; 

然后我试图创建多个视图:

for (int i=0;i<13;i++){ 

     grassImage = [[UIImageView alloc] init]; 

     int randNum = arc4random() % 320; //create random number for x position. 

     [grassImage setFrame:CGRectMake(randNum, 200.0, 50.0, 25.0)]; 
     [grassImage setTag:i+100]; 
     [grassImage setImage:[UIImage imageNamed:@"grass"]]; 

     [self.view addSubview:grassImage]; 
    } 

但是,当我试图访问该图像视图中使用标签,我只得到最后一个标签 - 112.

我的问题 - 我如何正确访问这个视图,使用他们的标签?

类似的问题:

+3

您根本不需要属性声明就可以使用它。 – Cyrille

+0

你如何_“使用标签访问此图像视图”_? – Amar

+0

只是使用这个。 UIImageView * imgViewRef =(UIImageView *)[self.view viewWithTag:TAG_NUMBER]; – Rajneesh071

回答

3

你只得到了最后一个,因为你是重现了同样的看法所有的时间。

摆脱变量,并添加您的看法是这样的:

for (int i=0;i<13;i++){ 
    UIImageView *grassImage = [[UIImageView alloc] init]; 

    int randNum = arc4random() % 320; //create random number for x position. 

    [grassImage setFrame:CGRectMake(randNum, 200.0, 50.0, 25.0)]; 
    [grassImage setTag:i+100]; 
    [grassImage setImage:[UIImage imageNamed:@"grass"]]; 

    [self.view addSubview:grassImage]; 
} 

而得到的意见:

UIImageView *imgView = [self.view viewWithTag:110]; 
+0

这很有道理,谢谢,我会试试这个 – ignotusverum

+4

你正在创建多个图像视图!答案是不正确的。购买你只能访问grassImage中的最后一个imageview。你应该仍然可以调用[self.view viewWithTag:100]; - [self.view viewWithTag:112];并访问每一个! –

+0

你说得对,Nils Ziehn – ignotusverum

0

使用此代码获取子视图与特定tag

UIImageView *imgViewRef = (UIImageView *)[self.view viewWithTag:TAG_NUMBER]; 
0

既然您是一次又一次地重新创建相同的图像,如果您访问grassImage它会给你你创建的最后一个imageview。相反,你可以像这样得到imageview。

for (UIImageView *imgView in self.view.subviews) { 
     if ([imgView isKindOfClass:[UIImageView class]]) { 
      NSLog(@"imageview with tag %d found", imgView.tag); 
     } 
    } 
相关问题