在imageview中添加4张图片,然后点击或滑动手势更改图片

时间:2012-05-26 04:27:09

标签: iphone uiimageview

我想在图像视图中添加四个图像。首先会看到一个图像。

每当点击或滑动图像视图时,它都会改变图像。

我想逐一更改4次imageview图像。

1 个答案:

答案 0 :(得分:2)

ToggleImageView.h

@interface ToggleImageView : UIImageView {
    NSArray *images;
    int currentIndex;
}

- (id)initWithImages:(NSArray *)theImages;

@end

ToggleImageView.m

#import "ToggleImageView.h"

@implementation ToggleImageView

- (id)initWithImages:(NSArray *)theImages {
    self = [self initWithImage:[theImages objectAtIndex:0]];

    if (self) {
        images = [theImages retain];
        currentIndex = 0;

        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
        [self addGestureRecognizer:tap];
        [tap release];

        self.userInteractionEnabled = YES;
    }

    return self;
}

-(void)dealloc {
    [images release];

    [super dealloc];
}

- (void)handleTap:(UITapGestureRecognizer *)sender {
    if (images.count > 0) {
        currentIndex++;
        if (currentIndex > images.count - 1) {
            currentIndex = 0;
        }

        self.image = [images objectAtIndex:currentIndex];
    }
}

@end

然后在你控制器的某个地方

ToggleImageView *tv = [[ToggleImageView alloc] initWithImages:[NSArray arrayWithObjects:[UIImage imageNamed:@"image1"], [UIImage imageNamed:@"image2"], [UIImage imageNamed:@"image3"], [UIImage imageNamed:@"image4"], nil]];
[self.view addSubview:tv];
[tv release];