使用按钮iPhone更改图像

时间:2010-08-01 10:54:47

标签: iphone image uibutton

我有UIImageView *picture

UIButton *next

- (IBAction)next {
}

我想更改视图上的图像,但仅限于图像等于...例如img1

但是使用相同的按钮我想也能够改变图片,如果图像= img2但是改为不同的图像(img3)

到目前为止,我有这段代码,但它给了我错误:

- (IBAction)next {
    if (picture UIImage = imageNamed:@"img01.jpg") {
    [picture setImage: [UIImage imageNamed:@"img02.jpg"
    }
    if (picture UIImage = imageNamed:@"img02.jpg") {
    [picture setImage: [UIImage imageNamed:@"img03.jpg"
 }
}

4 个答案:

答案 0 :(得分:1)

- (IBAction)next {
    picture.tag++;
    [picture setImage:[UIImage imageNamed:
             [NSString stringWithFormat:@"img%02d.jpg",1+(picture.tag%2)]
    ]];
}

应该是最简单的解决方案。

首次点击

修改,转到img02.jpg,再次点击返回img01.jpg。增加2以允许img03.jpg等。

答案 1 :(得分:1)

我现在想出来我所做的就是忘记将.jpg放在img%i的末尾;)

- (IBAction)next {
     static int index = 0;  // <-- here
    index++;
    // Set imageCount to as many images as are available
    int imageCount=16;
    if (index<=imageCount) {
        NSString* imageName=[NSString stringWithFormat:@"img%i", index];
        [picture setImage: [UIImage imageNamed: imageName]];
    }
}

答案 2 :(得分:0)

- (IBAction)next {
    if ([[picture image] isEqual: [UIImage imageNamed:@"img01.jpg"]]) {

       [picture setImage: [UIImage imageNamed:@"img02.jpg"]];

    } else if ([[picture image] isEqual: [UIImage imageNamed:@"img02.jpg"]]) {

       [picture setImage: [UIImage imageNamed:@"img03.jpg"]];
    }
}

此外,这是改变图像的一种非常基本的方式。更优雅的方法是拥有一个具有当前图像索引的全局int,因此单击“下一步”只会增加该计数。然后,如果存在具有该名称的图像,请切换到该图像:

//在Header.h中声明索引

index=0;

- (IBAction)next {
    index++;
    // Set imageCount to as many images as are available
    int imageCount=2;
    if (index<=imageCount) {
        NSString* imageName=[NSString stringWithFormat:@"img%02i", index];
        [picture setImage: [UIImage imageNamed: imageName]];
    }
}

答案 3 :(得分:0)

子类UIImageView并在标题中添加enum属性:

typedef enum _PictureType {
    PictureTypeFirstImage = 0,
    PictureTypeSecondImage,
    PictureTypeThirdImage,
    PictureTypes
} PictureType;

@interface MyImageView : UIImageView {
    PictureType type;
}

@property (readwrite) PictureType type;

在实施中:

@synthesize type;

初始化picture时:

[picture setImage:[UIImage imageNamed:@"img01.jpg"]];
picture.type = PictureTypeFirstImage;

在你的行动方法中:

- (IBAction) next {
    switch (picture.type) {
        case (PictureTypeFirstImage): {
            [picture setImage:[UIImage imageNamed:@"img02.jpg"]];
            picture.type = PictureTypeSecondImage;
            break;
        }
        case (PictureTypeSecondImage): {
            [picture setImage:[UIImage imageNamed:@"img03.jpg"]];
            picture.type = PictureTypeThirdImage;
            break;
        }
        default:
            break;
    }
}