在iPhone开发中UISwitch相当于其他UI库中的Checkbox,使用的时候推荐优先选用。但有些人还是会寻求在应用中使用他们更为熟悉的Checkbox,在一次项目的开发中我就遇到了这样的需求。本文将探讨一种比目前很多实现(比如iPhone UIButton tutorial : Custom Checkboxes)都更简洁的方案,主要原理就是充分利用UIButton的selected属性。

Checkbox声明:

@interface CheckBox : UIButton {
}

@end

Checkbox实现:
@implementation CheckBox

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initilization];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aCoder {
    if (self = [super initWithCoder:aCoder]) {
        [self initilization];
    }
    return self;
}

- (void)initilization {
    [self removeTarget:self action:nil forControlEvents:UIControlEventTouchUpInside];
    [self addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)onClick: (id)sender {
    self.selected = ![self isSelected];
}

@end

 

其中,initWithFrame和initWithCoder分别用于支持代码创建和IB创建CheckBox时的初始化工作,并在初始化时添加一个点击时的处理函数onClick。onClick用于选择状态取反。实际应用可以对UIControlEventTouchUpInside事件添加实际需要的处理函数。

 

简单吧!能够这样实现的原因就在于UIButton有Normal、Active、Selected以及Disabled等多种状态,本质上是包含了Checkbox所需的功能。通过上述的继承可以封装了点击后状态取反的逻辑,使得在将UIButton当做Checkbox使用的场景下更友好!