【发布时间】:2015-05-10 20:46:21
【问题描述】:
我有一个NSStrings 数组,我想将其用作UIImageView 的图像名称的来源。
当用户点击一个按钮时,我将一个新图像(数组中的下一个对象)加载到同一个图像视图中,这将是最终目标。实际上,我有一个可行但愚蠢的解决方案,这不是我想要的。我想将字符串名称从数组加载到UIImage,因为这个 if 语句可以用 30-40 个对象变得非常大,而且不太可靠。我对 for 循环不太满意,所以如果有人能告诉我如何使用 loop 或任何其他方式获得相同的结果,我将不胜感激。
- (IBAction)changeImage:(id)sender {
if (!self.userImageView.image) {
UIImage *image = [UIImage imageNamed:@"img1.png"];
self.userImageView.image = image;
self.currentDisplayedImageString = @"img1.png";
// self.currentDisplayedImageString is an ivar, type of NSString
}
else {
if ([self.currentDisplayedImageString isEqualToString:@"img1.png"]) {
UIImage *image = [UIImage imageNamed:@"img2.png"];
self.userImageView.image = image;
self.currentDisplayedImageString = @"img2.png";
}
if ([self.currentDisplayedImageString isEqualToString:@"img2.png"]) {
UIImage *image = [UIImage imageNamed:@"img3.png"];
self.userImageView.image = image;
self.currentDisplayedImageString = @"img3.png";
}
// AND SO ON...
}
}
【问题讨论】:
-
数组对象是预定义的吗?你能粘贴你的
for循环代码吗? -
嗯...您的图像名称真的是 img1、img2、img3 等吗?因为在这种情况下,您似乎不需要数组,因为名称本质上是对自己进行索引...
-
如果您的图片名称是这样的,您可以使用按钮的标签作为当前索引。在每个动作中,只需增加一次并从按钮的标签构建您的图像名称。不要忘记在递增后获取标签的模数:)
-
@LyndseyScott 不。图像名称会有所不同,并且可能从另一个视图控制器加载,但很高兴知道。谢谢
标签: ios objective-c nsarray