gpt4 book ai didi

ios - 使用按钮点击在 NSArray 对象上循环

转载 作者:行者123 更新时间:2023-11-28 19:49:24 24 4
gpt4 key购买 nike

我有一个 NSStrings 数组,我想将其用作 UIImageView 图像名称的来源。

当用户点击一个按钮时,我将新图像(数组中的下一个对象)加载到同一个 ImageView 中,这将是最终目标。实际上我有一个有效但愚蠢的解决方案,但这不是我想要的。我想将数组中的字符串名称加载到 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...

}
}

最佳答案

类似于:

@interface ViewController ()

@property (strong, nonatomic) UIImageView *imageView;
@property (strong, nonatomic) NSArray *imageNames;
@property (assign, nonatomic) int currentImageIndex;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

self.imageNames = @[@"img1", @"img2", @"img3", @"img4"];
self.currentImageIndex = -1;
}

- (void)changeImage {
if (++self.currentImageIndex == self.imageNames.count) {
self.currentImageIndex = 0;
}
self.imageView.image = [UIImage imageNamed:self.imageNames[self.currentImageIndex]];
}

@end

希望对您有所帮助!

关于ios - 使用按钮点击在 NSArray 对象上循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30151400/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com