开发者

UIButton that cycles through images when clicked

I have three images that I want to cycle through when clicking on a UIButton.

How would I go about doing this?

This is what I have so far, but it's not really working.

//the images
NSString* imageNames[] = {"MyFirstImage", "AnotherImage", whatever else};
int currentImageIndex = 0;

and

- (IBAction)change{
UIImage* imageToShow = [UIImage imageWithContentsOfFile:[[NSBund开发者_开发知识库le mainBundle] pathForResource: imageNames[currentImageIndex] ofType:@"png"];

if( currentImageIndex++ == sizeof(imageNames)/sizeof(NSString)) //check to see if you hit the last image
{
   currentImageIndex = 0; //start over
}
}

Ideas?

Any help will be greatly appreciated! Thanks!


Steven's suggestion to subclass UIButton is a good one. Once you get a some more experience with Objective C, you should consider his approach, but I can tell by the code you've posted that you're new to Objective C, so you may need to learn to use the basic Foundation classes first.

One reason your code isn't working is because you're trying to pass C string literals to pathForResource:, which requires an NSString object. NSStrings are objects in Objective C, not character pointers as they are in C. You can construct an NSString object using the literal syntax, @"quotes-with-an-at-in-front".

Here is code that implements the algorithm you attempted to write, using Objective C Foundation classes rather than C data types:

// YourController.h
@interface YourController :  UIViewController {
    NSArray *imageNames;
    NSInteger currentImageIndex;
    UIButton *yourButton;
}
@property (nonatomic, retain) NSArray *imageNames;
@property (nonatomic, retain) IBOutlet UIButton *yourButton; // Presumably connected in IB
- (IBAction)change;
@end
// YourController.m
#import "YourController.h"
@implementation YourController
@synthesize imageNames, yourButton;

- (void)dealloc {
    self.imageNames = nil;
    self.yourButton = nil;
    [super dealloc];
}

- (void)viewDidLoad {
    self.imageNames = [NSArray arrayWithObjects:@"MyFirstImage", @"AnotherImage", nil];
    currentImageIndex = 0;
    [super viewDidLoad];
}

- (IBAction)change {
    UIImage* imageToShow = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[imageNames objectAtIndex:currentImageIndex] ofType:@"png"];
    currentImageIndex++;
    if (currentImageIndex >= imageNames.count) {
        currentImageIndex = 0;
    }
    [yourButton setImage:imageToShow forState:UIControlStateNormal];
}

@end


You will want to subclass UIButton and add a new property that maintains state. You will also want to have three properties to maintain the images of the three new states. Then in your "drawRect:" method, swap out the standard buttons images based on your state and then call the [super drawRect:] method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜