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

时间:2015-05-10 12:26:59

标签: ios objective-c nsarray

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

当用户点击按钮时,我将新图像 - 数组中的下一个对象 - 加载到同一图像视图中,这将是最终目标。实际上我有一个工作但很愚蠢的解决方案,这不是我想要的。我想将数组中的字符串名称加载到UIImage,因为这个if语句在30-40对象时可能会变得非常大,而且不那么可靠。我对循环不太好,所以如果有人能告诉我如何用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...

    }
}

1 个答案:

答案 0 :(得分:2)

类似的东西:

@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
希望它有所帮助!