这就是我为一个按钮实现它的方式。您也可以将其用于更多按钮。
-(IBAction)ButtonAction
{
if (Flag==0)
{
Flag=1;
[myButton setImage:[UIImage imageNamed:@"checkbox-filled.png"] forState:UIControlStateNormal];
}
else
{
[myButton setImage:[UIImage imageNamed:@"checkbox.png"] forState:UIControlStateNormal];
Flag=0;
}
}
注意:如果您只想选中一个按钮,只需将所有其他按钮图像设置为 checkbox.png 和选中的 checkbox-filled.png。
编辑
您可以为复选框创建一个类,然后使用它。这是代码...
检查按钮.h
#import <Foundation/Foundation.h>
@interface CheckButton : UIButton {
BOOL _checked;
int chkButtonClickVal;
}
@property (nonatomic, setter=setChecked:) BOOL checked;
-(void) setChecked:(BOOL) check;
-(int)chkButtonClickVal;
@end
检查按钮.m
#import "CheckButton.h"
@implementation CheckButton
@synthesize checked = _checked;
-(id) init
{
if( self=[super init] )
{
chkButtonClickVal=0;
self.checked = NO;
[self addTarget:self action:@selector(OnCheck:) forControlEvents:UIControlEventTouchUpInside];
}
return self;
}
-(void) awakeFromNib
{
self.checked = NO;
[self addTarget:self action:@selector(OnCheck:) forControlEvents:UIControlEventTouchUpInside];
}
-(void) dealloc
{
chkButtonClickVal=0;
[super dealloc];
}
-(void) setChecked:(BOOL) check
{
_checked = check;
if( _checked )
{
UIImage* img = [UIImage imageNamed:@"checkbox-checked.png"];
[self setImage:img forState:UIControlStateNormal];
chkButtonClickVal=1;
}
else
{
UIImage* img = [UIImage imageNamed:@"checkbox.png"];
[self setImage:img forState:UIControlStateNormal];
chkButtonClickVal=2;
}
//NSLog(@"%d",chkButtonClickVal);
}
-(int)chkButtonClickVal
{
return chkButtonClickVal;
}
-(void) OnCheck:(id) sender
{
self.checked = !_checked;
}
@end
我以同样的方式做到了。试试你就能实现它。祝你好运 :)