从两个阵列交换ViewController中的图像

时间:2014-06-12 01:32:13

标签: ios arrays oop uiviewcontroller uiimageview

我是Objective C中编程的新手,我正在尝试使用不同的图片制作两个数组,并更新一个UIImageView。当用户点击ImageView时,我希望图像交换。

我得到的错误是:

"Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI size]: unrecognized selector sent to instance 0x8ccfbe0'"

ViewController.m

#import "ViewController.h"
#import "ImageStore.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation ViewController

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

    ImageStore *imageStore = [[ImageStore alloc] init];

    if ([_imageView isHighlighted]) {
        self.imageView.image = [[imageStore backImage] objectAtIndex: 0];
    }

    else
    {
        self.imageView.image = [[imageStore frontImage] objectAtIndex: 0];
    }

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

ImageStore.h

#import <Foundation/Foundation.h>

@interface ImageStore : NSObject
{
    NSArray *frontImage;
    NSArray *backImage;
}


@property (nonatomic, strong) NSArray *frontImage;
@property (nonatomic, strong) NSArray *backImage;

@end

ImageStore.m

#import "imageStore.h"

@implementation ImageStore

@synthesize frontImage, backImage;

-(NSArray *)frontImage
{
    if(!frontImage) frontImage = [[NSArray alloc] initWithObjects:@[@"Icon.png", @"OtherIcon.png"], nil];
    return frontImage;
}

-(NSArray *)backImage
{
    if(!backImage) backImage = [[NSArray alloc] initWithObjects:@[@"OtherIcon.png", @"Icon.png"], nil];
    return backImage;
}


@end

我使用数组的原因是,我打算将其放在CollectionView中,但是即使在这个级别上我似乎无法使模型正确。所以我一次采取这一步。

也许有更好的方法可以做到这一点?

非常感谢。

1 个答案:

答案 0 :(得分:0)

小心你的代码

self.imageView.image/*UIImage*/ = [[imageStore backImage] objectAtIndex: 0]/*NSString*/;

您的2个数组backImagefrontImage NSString 个对象的数组。

self.imageView.image UIImage

的属性

您无法将UIImage设置为NSString

您应该更改ImageStore.m

#import "imageStore.h"
...........
...........
-(NSArray *)frontImage
{
    if(!frontImage)
    frontImage = @[ [UIImage imageNamed:@"Icon.png"], [UIImage imageNamed:@"OtherIcon.png"] ];
    return frontImage;
}

-(NSArray *)backImage
{
    if(!backImage)
    backImage = @[ [UIImage imageNamed:@"OtherIcon.png"], [UIImage imageNamed:@"Icon.png"] ];
    return backImage;
}
............
............
@end