【问题标题】:XCODE Obj-C add UiimageView programatically in a forXCODE Objc 以编程方式在 for 中添加 UiimageView
【发布时间】:2015-03-13 18:37:09
【问题描述】:

所以我需要使用 for 循环以编程方式添加 3 张图像这是我的代码,这是不正确的,我只是尝试过。

for(int i = 1; i < 4; i++){
        UIImageView *[i] = [[UIImageView alloc] initWithFrame:CGRectMake([i]*50, 50, 250, 250)];

[self.view addSubview:[i]];
    }

在哪里 [i];将是 1 、 2 和 3 任何帮助将不胜感激。谢谢

【问题讨论】:

  • 此代码在同一位置创建 3 个 UIImageView。这就是为什么您无法在视图中看到所有三个。
  • 你的构造语法……太可怕了。您需要在输入[i] 的位置使用变量名。如:UIImageView *imageView = ... addSubview:imageView];.
  • 您在在一个语句中 对两个不同的事物使用相同的变量。你到底希望发生什么?

标签: ios objective-c uiimageview


【解决方案1】:

你的语法是错误的。这正是您所需要的。

for (int i=0;i<3;i++){
  UIImageView *image=[[UIImageView alloc] initWithFrame:CGRectMake(i*50, 50, 250, 250)];
  [self.view addSubView:image];
}

但是,这对您来说没有多大用处,因为您的图像不会从任何地方引用,因此您无法轻松填充或调整它们。

【讨论】:

  • 所有视图都将具有相同的框架
  • 正确,但这不是问题所在,为什么-1?问题中的代码示例显然没用。但是问题是代码不起作用。谁知道图像添加后的计划是什么。
  • CGRectMake([i]*50, 50, 250, 250)
【解决方案2】:

将变量名称从 [i] 更改为类似 imageToAdd 的名称。

【讨论】:

    【解决方案3】:
    CGFloat xMarging = 0;
    CGFloat imageOriginX = 0;
    CGFloat imageOriginY = 0;
    CGFloat imageWidth = 250;
    CGFloat imageHeight = 250;
    NSInteger numerOfImages = 3;
    for (NSInteger i = 0; i < numerOfImages; i++){
        [self.view addSubview:[[UIImageView alloc] initWithFrame:CGRectMake(xMarging + i * imageWidth,
                                                                            imageOriginY,
                                                                            imageWidth,
                                                                            imgageHeight)]];
    }
    

    假设您希望它们并排,如 [][][]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多