XCODE Objc 在 for 中以编程方式添加 imageView
XCODE Obj-C add UiimageView programatically in a for
所以我需要使用 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 任何帮助将不胜感激。谢谢
你的语法有误。这就是您所需要的。
for (int i=0;i<3;i++){
UIImageView *image=[[UIImageView alloc] initWithFrame:CGRectMake(i*50, 50, 250, 250)];
[self.view addSubView:image];
}
但是,这对您没有太大用处,因为您的图像未从任何地方引用,因此您无法轻松填充或调整它们。
将变量名从 [i]
更改为类似 imageToAdd
的名称。
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)]];
}
假设您希望它们并排放置,如 [][][]
所以我需要使用 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 任何帮助将不胜感激。谢谢
你的语法有误。这就是您所需要的。
for (int i=0;i<3;i++){
UIImageView *image=[[UIImageView alloc] initWithFrame:CGRectMake(i*50, 50, 250, 250)];
[self.view addSubView:image];
}
但是,这对您没有太大用处,因为您的图像未从任何地方引用,因此您无法轻松填充或调整它们。
将变量名从 [i]
更改为类似 imageToAdd
的名称。
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)]];
}
假设您希望它们并排放置,如 [][][]