【问题标题】:Create multiple UIImageViews programmatically以编程方式创建多个 UIImageViews
【发布时间】:2013-10-23 13:13:34
【问题描述】:

我想用不同的标签以编程方式创建多个 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。

我的问题 - 如何使用它们的标签正确访问这些视图?

类似问题:

【问题讨论】:

  • 你根本不需要属性声明来使用它。
  • 您如何“使用标签访问此图像视图”
  • 就用这个吧。 UIImageView *imgViewRef = (UIImageView *)[self.view viewWithTag:TAG_NUMBER];

标签: ios iphone objective-c uiimageview programmatically-created


【解决方案1】:

您只得到最后一个,因为您一直在重新创建相同的视图。

去掉那个变量,像这样添加你的视图:

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];

【讨论】:

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

由于您一次又一次地重新创建相同的图像,如果您访问grassImage,它将为您提供您创建的最后一个图像视图。相反,您可以像这样获得图像视图。

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

【讨论】:

    【解决方案3】:

    使用此代码获取具有特定tag 的子视图,

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-06
      • 2018-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      相关资源
      最近更新 更多