由于您有自定义按钮,最好的解决方案是根据您拥有的复选框的状态更改按钮的图像(您提到这个想法是创建类似于复选框按钮的东西)。
UIButton 类中有一个名为“setImage:forState:”的方法。您可以使用上述方法更改按钮内的图像。在此处查看更多信息
示例我如何查看代码(您可以以另一种方式查看):
// bool property
@property (assign) BOOL isChecked;
....
// custom button
UIButton *theCheckboxButton = ;
[theCheckboxButton setImage:[UIImage imageNamed:@"Unchecked"] forState:UIControlStateNormal];
[theCheckboxButton setImage:[UIImage imageNamed:@"Checked"] forState:UIControlStateSelected];
[theCheckboxButton addTarget:self action:@selector(checkBoxButtonAction:) forControlEvents: UIControlEventTouchUpInside];
...
// handler
- (void)checkBoxButtonAction:(UIButton *)aCheckBox
{
self.isChecked = !self.isChecked;
[aCheckBox setImage:[UIImage imageNamed:(self.isChecked ? @"Checked" : @"Unchecked")] forState:UIControlStateNormal];
[theCheckboxButton setImage:[UIImage imageNamed:(self.isChecked ? @"Unchecked" : @"Checked")] forState:UIControlStateSelected];
}
编辑:
// images from not external resources
@property (strong) UIImage *checkedImage;
@property (strong) UIImage *uncheckedImage;
// bool property
@property (assign) BOOL isChecked;
...
// custom button
UIButton *theCheckboxButton = ;
[theCheckboxButton setImage:self.uncheckedImage forState:UIControlStateNormal];
[theCheckboxButton setImage:self.checkedImage forState:UIControlStateSelected];
[theCheckboxButton addTarget:self action:@selector(checkBoxButtonAction:) forControlEvents: UIControlEventTouchUpInside];
...
// handler
- (void)checkBoxButtonAction:(UIButton *)aCheckBox
{
self.isChecked = !self.isChecked;
[aCheckBox setImage:self.isChecked ? self.checkedImage : self.uncheckedImage] forState:UIControlStateNormal];
[theCheckboxButton setImage:(self.isChecked ? self.uncheckedImage : self.checkedImage) forState:UIControlStateSelected];
}