iOS系统中没有自带的星星评分功能,需要自己封装。星星评分功能是整个工程的一个需求,但是代码的封装则是一个代码功底和编程思维的考验。
星星评分封装代码部分:
#import <UIKit/UIKit.h>
@interface StarsView : UIView
// 分值,范围1~5,默认5
@property (nonatomic, assign) CGFloat score;
// block 传值
@property (nonatomic, copy) void (^selectedStars)(CGFloat starScore);
@end
设定变动参数,这里最好是定义成全局的,修改起来比较方便
#import "StarsView.h"
#define SELECT_STAR @"icon_star_green"
#define UNSELECT_STAR @"icon_star_gray"
#define DEFALUT_STAR_NUMBER 5
#define ANIMATION_TIME_INTERVAL 0.1
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
@interface StarsView ()
// 选中图层
@property (nonatomic, strong) UIView * selectView;
// 未选中图层
@property (nonatomic, strong) UIView * unSelectView;
// 星星的数量
@property (nonatomic, assign) NSInteger numberOfStar;
@end
@implementation StarsView
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor whiteColor];
// 设置星星布局
[self configStarScoreView];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
__weak typeof(self) weakself = self;
[UIView animateWithDuration:ANIMATION_TIME_INTERVAL animations:^{
weakself.selectView.frame = CGRectMake(0, 0, weakself.bounds.size.width / weakself.numberOfStar * weakself.score, weakself.bounds.size.height);
}];
}
// 设置星星布局
- (void)configStarScoreView {
_numberOfStar = DEFALUT_STAR_NUMBER; // 默认星星为5颗
// 选中图层
_selectView = [self createStarViewWithImage:SELECT_STAR];
// 未选中图层
_unSelectView = [self createStarViewWithImage:UNSELECT_STAR];
[self addSubview:self.unSelectView];
[self addSubview:self.selectView];
// 添加手势
UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(starTapGesture:)];
tapGesture.numberOfTapsRequired = 1;
[self addGestureRecognizer:tapGesture];
}
// 星星触摸手势
- (void)starTapGesture:(UITapGestureRecognizer *)gesture {
// 定位手势的位置
CGPoint tapPoint = [gesture locationInView:self];
CGFloat offset = tapPoint.x;
// 星星的位置
CGFloat positionStar = offset / (self.bounds.size.width / self.numberOfStar);
// 分数取整
self.score = ceilf(positionStar);
}
#pragma mark - 创建星星图层
- (UIView *)createStarViewWithImage:(NSString *)imageName {
UIView *view = [[UIView alloc] initWithFrame:self.bounds];
view.clipsToBounds = YES;
view.backgroundColor = [UIColor clearColor];
for (NSInteger i = 0; i < self.numberOfStar; i ++) {
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
CGFloat with = self.bounds.size.width / self.numberOfStar;
imageView.frame = CGRectMake(i * with, 0, with, self.bounds.size.height);
imageView.contentMode = UIViewContentModeScaleAspectFit;
[view addSubview:imageView];
}
return view;
}
#pragma mark - GET and SET
- (void)setScore:(CGFloat)score {
if (_score != score) {
_score = score;
}
if (self.selectedStars) {
self.selectedStars(score);
}
[self setNeedsLayout];
}
@end