自定义复选框无法按预期工作

时间:2013-04-23 00:17:59

标签: xcode uibutton

我正在尝试创建这个检查按钮,然后在我的项目中调用那个检查按钮,并通过添加一个像它应该的图像来工作,但我甚至无法将它带到NSLog .. 。出于测试目的......

下面是按钮.h和.m文件。以及我正在调用按钮并尝试使用的视图......

CheckButton.h     #import

@interface CheckButton : UIButton {
    BOOL _checked;
}

@property (nonatomic, setter=setChecked:) BOOL checked;

-(void) setChecked:(BOOL)check;

@end

CheckButton.m

#import "CheckButton.h"

@implementation CheckButton
@synthesize checked = _checked;

-(id) init {
    if (self=[super init]) {
        self.checked = NO;
        [self addTarget:self action:@selector(setChecked:) forControlEvents:UIControlEventTouchUpInside];
    }
    return self;
}

-(void) awakeFromNib {
    self.checked = NO;
    [self addTarget:self action:@selector(OnCheck:) forControlEvents:UIControlEventTouchUpInside];

}

- (void) setChecked:(BOOL)check{
    _checked = check;
    if(_checked) {
        UIImage *img = [UIImage imageNamed:@"check.png"];
        [self setImage:img forState:UIControlStateNormal];
         NSLog(@"Checked");
    } else {
        UIImage *img = [UIImage imageNamed:@"uncheck.png"];
        [self setImage:img forState:UIControlStateNormal];
         NSLog(@"UnChecked");
    }
}

-(void) OnCheck:(id) sender {
    self.checked = _checked;
}


@end

GoToBedPopUp.h

#import "CheckButton.h"

@interface GoToBedPopup : PopupContainer{
    IBOutlet  CheckButton *checkboxButton;
}

// Checkboxes - (CheckButton)
@property (nonatomic, strong) CheckButton *checkHR;

@end

GoToBedPopUp.m

#import "GoToBedPopup.h"

@implementation GoToBedPopup


@synthesize checkHR, checkO2, checkMovement, checkNoise, checkSkinTemp;

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];

    // Checkbox Button
    checkHR = [[CheckButton alloc] initWithFrame:CGRectMake(17, 31, 23, 23)];

    return self;
}

1 个答案:

答案 0 :(得分:1)

嗨,我测试了你的代码一切都好,你只改变了一件事......

- (void) setChecked:(BOOL)check{
    _checked = !check; //** this is the only one change needed 
    if(_checked) {
        UIImage *img = [UIImage imageNamed:@"Check.png"];
        [self setImage:img forState:UIControlStateNormal];
        NSLog(@"Checked");
    } else {
        UIImage *img = [UIImage imageNamed:@"Uncheck.png"];
        [self setImage:img forState:UIControlStateNormal];
        NSLog(@"UnChecked");
    }
}

示例项目here