我建議你製作一個自定義按鈕。以下轉介代碼。
首先,製作下面的按鈕。 文件 - 新建 - 文件 - 可可觸摸Objective-C類 FavoriteButton.h
#import <UIKit/UIKit.h>
@interface FavoriteButton : UIButton
@property (nonatomic, assign) BOOL isFavorite;
@end
FavoriteButton.m
#import "FavoriteButton.h"
@implements FavoriteButton : UIButton
@synthesize isFavorite;
...
@end
硒cond,在Storyboard中鏈接一個FavoriteButton。參考下面的圖片。 在故事板的右側面板中。之前,點擊您最初的UIButton
YourViewController.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];
}
}
我嘗試這樣做,但我得到4個錯誤:房產 「isFavorite」 關於類型的對象未找到UIButton x 2和「UIButton中沒有可見的@interface聲明選擇器」setHighlighted「x 2.並且,如果要將添加的通知放置在'if'塊中,並且要刪除fav的通知將被放置在'其他'塊?還是我誤解了這個? – ingenspor 2012-08-06 03:13:26
我編輯後。請檢查出來。 – 2012-08-06 03:27:26
很好,非常感謝! – ingenspor 2012-08-08 06:34:24