我建议您制作一个自定义按钮。以下参考代码。
首先,制作一个以下按钮。File-New-File-Cocoa Touch-Objective-C 类
FavoriteButton.h
#import <UIKit/UIKit.h>
@interface FavoriteButton : UIButton
@property (nonatomic, assign) BOOL isFavorite;
@end
收藏按钮.m
#import "FavoriteButton.h"
@implements FavoriteButton : UIButton
@synthesize isFavorite;
...
@end
其次,在 Storyboard 中链接一个 FavoriteButton。参考下图。位于故事板的右侧面板中。之前,点击你原来的 UIButton
你的ViewController.h
#import <UIKit/UIKit.h>
#import "FavoriteButton.h"
@interface YourViewController : UIViewController
@property (retain, nonatomic) IBOutlet FavoriteButton *favoriteButton;
@end
@implements YourViewController : UIViewController
@synthesize favoriteButton;
-(void) viewDidLoad
{
self.favoriteButton = [[FavoriteButton alloc] initWithFrame:...]];
//favoriteButton.isFavorite = NO; (already set in storyboard)
...
}
-(IBAction)favoriteButtonPressed:(id)sender
{
[self performSelector:@selector(manageHighlightAndFave:) withObject:sender afterDelay:0];
}
- (void)manageHighlightAndFave:(FavoriteButton *)favButton {
[[NSNotificationCenter defaultCenter] postNotificationName:@"ItemSelected"
object:selectedObject];
//true-false(YES-NO) Toggled. but isFavorite property is Must be initialized to false.
favButton.isFavorite = !favButton.isFavorite;
if(favButton.isFavorite)
{
favButton.imageView.image = [UIImage imageNamed:@"your_star_image"];
[favButton setHighlighted:YES];
}
else
{
favButton.imageView.image = nil;
[favButton setHighlighted:NO];
}
}