//评价星星控件用法
StarView *startView = [[StarView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
startView.startNum = 4;
startView.defalutImage = [UIImage imageNamed:@" "];
startView.selectedImage = [UIImage imageNamed:@" "];
[self.view addSubview:startView];
星星控件:
#import "StarView.h"
//星星的大小
#define startBtnSize 30
//星星的间隙
#define startInterval 5
@implementation StarView
- (instancetype)initWithFrame:(CGRect)frame {
if (self == [super initWithFrame:frame]) {
[self setBackgroundColor:[UIColor whiteColor]];
}
return self;
}
- (void)drawRect:(CGRect)rect {
self.tag = 11;
CGFloat originX = (rect.size.width-_startNum*startBtnSize-(_startNum-1)*startInterval) * 0.5;
CGFloat originY = (rect.size.height-startBtnSize)*0.5;
for (int i = 0 ; i <</span> _startNum; i++) {
UIButton *startButton = [[UIButton alloc]initWithFrame:CGRectMake(originX + (startInterval+startBtnSize) * i, originY, startBtnSize, startBtnSize)];
startButton.tag = i ;
[startButton setImage:_defalutImage forState:UIControlStateNormal];
[startButton setImage:_selectedImage forState:UIControlStateSelected];
[startButton addTarget:self action:@selector(startBtnClick:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:startButton];
}
//点击手势
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
[self addGestureRecognizer:pan];
}
- (void)startBtnClick:(UIButton *)sender {
for (int i = 0; i <</span> _startNum; i++) {
if (i <= sender.tag) {
if (sender.tag == 0) {
UIButton *button = [self viewWithTag:i];
button.selected = !button.selected;
if (button.selected == YES) {
self.score = 1;
} else {
self.score = 0;
}
} else {
UIButton *button = [self viewWithTag:i];
button.selected = YES;
self.score = sender.tag;
}
} else {
UIButton *button = [self viewWithTag:i];
button.selected = NO;
}
}
}
- (void)pan:(UIPanGestureRecognizer *)gesture {
CGPoint point = [gesture locationInView:self];
if (point.x > 0 && point.x <</span> _startNum*startBtnSize+(_startNum - 1)*startInterval) {
CGFloat k = point.x/(startBtnSize+startInterval);
for (int i = 0; i <</span> _startNum; i++) {
if (k >= i && k < i+1) {
k = i;
}
}
UIButton *button = [self viewWithTag:k];
[self startBtnClick:button];
}
}
@end