UIButton配置带有高亮显示

时间:2012-08-06 00:36:31

标签: iphone objective-c xcode

我已经创建了一个UIbutton(在故事板中)将对象添加到收藏夹列表,但是我在配置它时遇到了问题。这会将对象添加到收藏夹,但如何取消喜欢它?

我一直在寻找和思考一段时间,我的想法是在manageHighlightAndFave中制作一些if语句:if favButton state = highlighted,从收藏夹中删除并删除突出显示。否则,添加到收藏夹并添加突出显示。这是好事,或者我正在尝试做什么的首选方式是什么?我很喜欢一个例子,因为我是编程新手。

-(IBAction)favoriteButtonPressed:(id)sender
{
    [self performSelector:@selector(manageHighlightAndFave:) withObject:sender afterDelay:0];
}

- (void)manageHighlightAndFave:(UIButton*)favButton {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ItemSelected"
                                                        object:selectedObject];
    [favButton setHighlighted:YES];
}

PS。与故事板中的“触地”相关联。

1 个答案:

答案 0 :(得分:1)

我建议你制作一个自定义按钮。以下参考代码。

首先,制作一个关注按钮。 File-New-File-Cocoa Touch-Objective-C类 enter image description here enter image description here 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

其次,在Storyboard中链接一个FavoriteButton。参考下面的图像。 在故事板的右侧面板中。之前,点击你原来的UIButton

enter image description here

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];
    }
}