可自定义按钮个数(buttonCoount),以及选择是否需要多选(isMutiple),
1)自定义UIImageView类的声明,添加点击事件,添加判断是否被点击属性
@interface MyImageView : UIImageView
/**
* 给自定义的控件添加点击事件
*/
@property(nonatomic, retain) id target;
@property(nonatomic, assign) SEL action;
-(void)addTarget:(id) target action:(SEL)action;
/**
* 给自定义的控件添加表示状态的属性(代表是否被选中)
*/
@property(nonatomic, assign, getter = isSelected) BOOL selected;
@end
自定义UIImageView的方法实现
@implementation MyImageView
/**
* 为自定义的UIImageView控件添加点击事件
*
* @param target 方法作用的目标对象
* @param action 需要执行的方法
*/
-(void)addTarget:(id)target action:(SEL)action{
self.target = target;
self.action = action;
}
/**
* 实现点击事件的方法,系统提供,自动检测屏幕触摸
*
* @param touches 集合类型,收集关于触摸的信息
* @param event 用于收集关于事件的信息如:类型,时间间隔等
*/
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self.target performSelector:self.action withObject:self];
}
@end
声明部分
#import "MyImageView.h"
@interface RadioOrMultipleChoiceButton : UIView
/**
* 自定义按钮个数(默认为控件的高除以宽)
*/
@property(nonatomic, assign) int buttonCount;
/**
* 自定义的UIImageView类型控件
*/
@property(nonatomic, retain) MyImageView *imageView;
/**
* 是否多选(默认单选)
*/
@property(nonatomic, assign) BOOL isMultiple;
@end
实现部分
#import "AppDelegate.h"
//按钮数 = 控件的高/控件的宽
#define kButtonCount (self.frame.size.height)/(self.frame.size.width)
//控件的宽
#define kButtonWith (self.frame.size.width)
//控件的高
#define kButtonHeight (self.frame.size.height)
//获得按钮的背景图片
#define kButtonImage (((MyImageView *)[self viewWithTag:i+1]).image)
@implementation RadioOrMultipleChoiceButton
-(instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
//判断是否设置了按钮数量,并且用户设置的按钮数是否大于控件最大按钮数,如果满足条件,将按钮设置为最大按钮数
if (self.buttonCount == 0 || self.buttonCount > kButtonCount) {
self.buttonCount = kButtonCount;
}
for (int i = 0; i < self.buttonCount; i++) {
//设置按钮位置和大小
self.imageView = [[MyImageView alloc] initWithFrame:CGRectMake(0, (int)(i * kButtonWith + i * (kButtonHeight - kButtonWith * self.buttonCount)/self.buttonCount), kButtonWith, kButtonWith)];
//设置默认图片
self.imageView.image = [UIImage imageNamed:@"check"];
self.imageView.tag = i + 1;
//设置imageView的用户交互状态
self.imageView.userInteractionEnabled = YES;
[self.imageView addTarget:self action:@selector(isMutable:)];
[self addSubview:self.imageView];
[self.imageView release];
}
}
return self;
}
-(void)isMutable:(MyImageView *)sender{
//isMultiple判断是否多选,默认为单选(isMultiple)
if(self.isMultiple){
//调用多选的方法
[self changePhoto:sender];
}else {
//单选的实现
for(int i = 0; i < self.buttonCount; i++){
if ([kButtonImage isEqual:[UIImage imageNamed:@"checked"]]) {
kButtonImage = [UIImage imageNamed:@"check"];
}
}
sender.image = [UIImage imageNamed:@"checked"];
}
}
//多选实现
-(void)changePhoto:(MyImageView *)sender{
//每次点击改变按钮的状态(选中改为非选中,反之亦然)
sender.selected = !sender.isSelected;
if (sender.selected) {
sender.image = [UIImage imageNamed:@"checked"];
}else{
sender.image = [UIImage imageNamed:@"check"];
}
}