I have a UIImageView *picture
and开发者_JAVA技巧 a UIButton *next
and an
- (IBAction)next {
}
I want to change the image on the view but only if the image equals... for example img1
But using the same button I want to also be able to change the picture if the image = img2 but to a different image (img3)
So far I have this code but it gives me errors:
- (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"
}
}
- (IBAction)next {
picture.tag++;
[picture setImage:[UIImage imageNamed:
[NSString stringWithFormat:@"img%02d.jpg",1+(picture.tag%2)]
]];
}
should be the simplest solution.
edit on first click, goes to img02.jpg
, on second click back to img01.jpg
again. Increase the 2
to allow for img03.jpg
etc.
I figured it out now all I did was forget to put .jpg on the end of the 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]];
}
}
Subclass UIImageView
and add a enum
property in the header:
typedef enum _PictureType {
PictureTypeFirstImage = 0,
PictureTypeSecondImage,
PictureTypeThirdImage,
PictureTypes
} PictureType;
@interface MyImageView : UIImageView {
PictureType type;
}
@property (readwrite) PictureType type;
In the implementation:
@synthesize type;
When initializing your picture
:
[picture setImage:[UIImage imageNamed:@"img01.jpg"]];
picture.type = PictureTypeFirstImage;
In your action method:
- (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;
}
}
- (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"]];
}
}
Also, this is a pretty rudimentary way of changing the image. A more elegant way would be to have a global int
that had the current image index, so clicking "next" would simply increase that count. Then, if an image exists with that name, switch to it:
// Declare index in 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]];
}
}
精彩评论