一个星形评分控件的封装

前言

很久没有更新简书了,这段时间一直在忙着撸代码。项目的事情暂时总算是告一段落了,打开简书一看,整个六月份一篇都没有写。本来还想强行解释一波的,算了,总结一句话,还是懒。新项目设计妹纸正在做设计稿,看到项目中有一个星形评分的控件,闲来无事,找了几个网上的看了一下,都不是很满足自己的需求,所以自己动手实现了一下。

效果图

效果图.gif

实现思路

  • 创建前后两个frame相等的视图
  • 在创建好的视图上循环添加需要个数的UIImageView,并设置对应的图片。
  • 根据手指在控件上的位置获取X轴上的偏移量,计算成分数。

代码实现

大致的实现思路了解了,接下来要做的就是编码实现。首先创建一个类 XKStarRateView 继承自 UIView,在 XKStarRateView.h 中,声明一些初始的构造方法。

#import <UIKit/UIKit.h>

typedef NS_ENUM(NSInteger, XKStarRateStyle) {
    
    XKWholeStarStyle = 0,
    
    XKHalfStarStyle = 1,
    
    XKIncompleteStarStyle = 2
};

typedef void(^XKStarRateSelectedBlock)(CGFloat score);

@class XKStarRateView;

@protocol XKStarRateViewDelegate <NSObject>

- (void)starRateView:(XKStarRateView *)starRateView currentScore:(CGFloat)currentScore;

@end


@interface XKStarRateView : UIView

/// 是否显示动画(默认为NO)
@property (nonatomic, assign) BOOL isAnimation;

/// 评分样式 (XKWholeStarStyle 整星评论 XKHalfStarStyle 半星评论 XKIncompleteStarStyle 不完整星评论)
@property (nonatomic, assign) XKStarRateStyle rateStyle;

/// 代理
@property (nonatomic, weak) id<XKStarRateViewDelegate> delegate;

/**
 初始化方法

 @param frame 控件frame
 @param numberOfStars 星星数量
 @param rateStyle 评分样式 (XKWholeStarStyle 整星评论 XKHalfStarStyle 半星评论 XKIncompleteStarStyle 不完整星评论)
 @param isAnimation 是否动画
 @param delegate 代理
 @return XKStarRateView
 */
- (instancetype)initWithFrame:(CGRect)frame
                numberOfStars:(NSInteger)numberOfStars
                    rateStyle:(XKStarRateStyle)rateStyle
                  isAnination:(BOOL)isAnimation
                     delegate:(id<XKStarRateViewDelegate>)delegate;


/**
 初始化方法

 @param frame 控件frame
 @param starRateSelectedBlock 点击星星的回调
 @return XKStarRateView
 */
- (instancetype)initWithFrame:(CGRect)frame
        starRateSelectedBlock:(XKStarRateSelectedBlock)starRateSelectedBlock;


/**
 初始化方法

 @param frame 控件frame
 @param numberOfStars 星星数量
 @param rateStyle 评分样式 (XKWholeStarStyle 整星评论 XKHalfStarStyle 半星评论 XKIncompleteStarStyle 不完整星评论)
 @param isAnimation 是否动画
 @param starRateSelectedBlock 点击星星的回调
 @return XKStarRateView
 */
- (instancetype)initWithFrame:(CGRect)frame
                numberOfStars:(NSInteger)numberOfStars
                    rateStyle:(XKStarRateStyle)rateStyle
                  isAnination:(BOOL)isAnimation
        starRateSelectedBlock:(XKStarRateSelectedBlock)starRateSelectedBlock;

@end

这里提供了三种样式供选择,整星,半星,任意星。以及代理和Block两种方式获得当前控件显示所对应的分数。还提供了一个可选动画的属性。

在实现的过程中,首先定义一些必要的属性参数。

typedef void(^completeBlock)(CGFloat currentScore);

@interface XKStarRateView ()

@property (nonatomic, strong) UIView *foregroundStarView;

@property (nonatomic, strong) UIView *backgroundStarView;

@property (nonatomic, assign) NSInteger numberOfStars;

@property (nonatomic, assign) CGFloat currentScore;

@property (nonatomic, strong) completeBlock complete;

@end

接下来声明一个方法创建需要的视图

/**
 根据图片名称创建StarView

 @param imageName 图片名称
 */
- (UIView *)createStarViewWithImageName:(NSString *)imageName {
    
    UIView *view = [[UIView alloc] initWithFrame:self.bounds];
    
    view.clipsToBounds = YES;
    
    view.backgroundColor = [UIColor clearColor];
    
    for (NSInteger i = 0; i < self.numberOfStars; i ++) {
        
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
        
        imageView.frame = CGRectMake(i * self.bounds.size.width / self.numberOfStars, 0, self.bounds.size.width / self.numberOfStars, self.bounds.size.height);
        
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        
        [view addSubview:imageView];
    }
    
    return view;
}

初始化视图

/**
 初始化评论视图
 */
- (void)initStarView {
    
    self.foregroundStarView = [self createStarViewWithImageName:NormalImageName];
    
    self.backgroundStarView = [self createStarViewWithImageName:SelectedImageName];
    
    self.foregroundStarView.frame = CGRectMake(0, 0, self.bounds.size.width * _currentScore / self.numberOfStars, self.bounds.size.height);
    
    [self addSubview:self.backgroundStarView];
    
    [self addSubview:self.foregroundStarView];
}

视图什么的都创建好了,接着处理事件,这里的点击事件和滑动事件我并没有去给视图添加手势,而是直接放到视图的Touch事件中去处理的。

#pragma mark -- touch事件处理

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [event touchesForView:self];
    
    NSSet *allTouches = [event allTouches];
    
    UITouch *touch = [allTouches anyObject];
    
    CGPoint point = [touch locationInView:[touch view]];
    
    CGFloat offset = point.x;
    
    CGFloat realStarScore = offset / (self.bounds.size.width / self.numberOfStars);
    
    [self handleRealStarScore:realStarScore];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [event touchesForView:self];
    
    NSSet *allTouches = [event allTouches];
    
    UITouch *touch = [allTouches anyObject];
    
    CGPoint point = [touch locationInView:[touch view]];
    
    CGFloat offset = point.x;
    
    CGFloat realStarScore = offset / (self.bounds.size.width / self.numberOfStars);
    
    [self handleRealStarScore:realStarScore];
}

根据偏移量计算最终的评分,这里根据选择不同的样式计算方法有不一样的地方。

/**
 根据偏移量计算最终的评分

 @param realStarScore 真实的偏移量
 */
- (void)handleRealStarScore:(CGFloat)realStarScore {
    
    switch (_rateStyle) {
            
        case XKWholeStarStyle:
            
            self.currentScore = ceilf(realStarScore);
            
            break;
            
        case XKHalfStarStyle:
            
            self.currentScore = roundf(realStarScore) > realStarScore ? ceilf(realStarScore) : (ceilf(realStarScore) - 0.5);
            
            break;
            
        case XKIncompleteStarStyle:
            
            self.currentScore = realStarScore;
            
            break;
            
        default:
            
            break;
    }
}

这里主要的就是两个C语言函数的使用。

  • round:如果参数是小数,则求本身的四舍五入。
  • ceilf:如果参数是小数,则向上取整。

拿到当前的偏移量计算出来的分数之后,在setter方法中将这个值传出去。并且刷新视图。

- (void)setCurrentScore:(CGFloat)currentScore {
    
    if (_currentScore == currentScore) {
        
        return;
    }
    
    if (currentScore < 0) {
        
        _currentScore = 0;
        
    } else if (currentScore > _numberOfStars) {
        
        _currentScore = _numberOfStars;
        
    } else {
        
        _currentScore = currentScore;
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(starRateView:currentScore:)]) {
        
        [self.delegate starRateView:self currentScore:_currentScore];
    }
    
    if (self.complete) {
        
        _complete(_currentScore);
    }
    
    [self setNeedsLayout];
}

- (void)layoutSubviews 方法中,去改变 foregroundStarView 的frame即可。

- (void)layoutSubviews {
    
    [super layoutSubviews];
    
    __weak XKStarRateView *weakSelf = self;
    
    CGFloat animationTimeInterval = self.isAnimation ? 0.2 : 0;
    
    [UIView animateWithDuration:animationTimeInterval animations:^{
        
        weakSelf.foregroundStarView.frame = CGRectMake(0, 0, weakSelf.bounds.size.width * weakSelf.currentScore / self.numberOfStars, weakSelf.bounds.size.height);
    }];
}

到这里,基本的功能就做完了,构造方法中只需要初始化部分参数就好了。运行程序,发现有一个问题,就是当你选择了一个分数之后,在 XKWholeStarStyleXKHalfStarStyle 两种样式中,始终没有办法将评分设置为0,问题出在 - (void)handleRealStarScore:(CGFloat)realStarScore 这个方法中使用到的两个C语言函数。这里最后也没有去在想其他的方式来实现。在这个方法中手动的设置了一下,当 realStarScore比0.5还小的时候,就直接让分数为0。简单粗暴。

/**
 根据偏移量计算最终的评分

 @param realStarScore 真实的偏移量
 */
- (void)handleRealStarScore:(CGFloat)realStarScore {
    
    switch (_rateStyle) {
            
        case XKWholeStarStyle:
            
            if (realStarScore < 0.5) {
                
                self.currentScore = 0;
                
            } else {
                
                self.currentScore = ceilf(realStarScore);
            }
            
            break;
            
        case XKHalfStarStyle:
            
            if (realStarScore < 0.4) {
                
                self.currentScore = 0;
                
            } else {
                
                self.currentScore = roundf(realStarScore) > realStarScore ? ceilf(realStarScore) : (ceilf(realStarScore) - 0.5);
            }
            
            break;
            
        case XKIncompleteStarStyle:
            
            self.currentScore = realStarScore;
            
            break;
            
        default:
            
            break;
    }
}

最后,整个实现文件的代码如下

#import "XKStarRateView.h"

#define NormalImageName @"b27_icon_star_yellow"

#define SelectedImageName @"b27_icon_star_gray"

typedef void(^completeBlock)(CGFloat currentScore);

@interface XKStarRateView ()

@property (nonatomic, strong) UIView *foregroundStarView;

@property (nonatomic, strong) UIView *backgroundStarView;

@property (nonatomic, assign) NSInteger numberOfStars;

@property (nonatomic, assign) CGFloat currentScore;

@property (nonatomic, strong) completeBlock complete;

@end

@implementation XKStarRateView

#pragma mark -- 构造方法

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        _numberOfStars = 5;
        
        _rateStyle = XKWholeStarStyle;
        
        [self initStarView];
    }
    
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
                numberOfStars:(NSInteger)numberOfStars
                    rateStyle:(XKStarRateStyle)rateStyle
                  isAnination:(BOOL)isAnimation
                     delegate:(id<XKStarRateViewDelegate>)delegate {
    
    if (self = [super initWithFrame:frame]) {
        
        _numberOfStars = numberOfStars;
        
        _rateStyle = rateStyle;
        
        _isAnimation = isAnimation;
        
        _delegate = delegate;
        
        [self initStarView];
    }
    
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
        starRateSelectedBlock:(XKStarRateSelectedBlock)starRateSelectedBlock{
    
    if (self = [super initWithFrame:frame]) {
        
        _numberOfStars = 5;
        
        _rateStyle = XKWholeStarStyle;
        
        _complete = ^(CGFloat currentScore){
            
            starRateSelectedBlock(currentScore);
        };
        
        [self initStarView];
    }
    
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
                numberOfStars:(NSInteger)numberOfStars
                    rateStyle:(XKStarRateStyle)rateStyle
                  isAnination:(BOOL)isAnimation
        starRateSelectedBlock:(XKStarRateSelectedBlock)starRateSelectedBlock {
    
    if (self = [super initWithFrame:frame]) {
        
        _numberOfStars = numberOfStars;
        
        _rateStyle = rateStyle;
        
        _isAnimation = isAnimation;
        
        _complete = ^(CGFloat currentScore) {
            
            starRateSelectedBlock(currentScore);
        };
        
        [self initStarView];
    }
    
    return self;
}

#pragma mark -- 私有方法

/**
 初始化评论视图
 */
- (void)initStarView {
    
    self.foregroundStarView = [self createStarViewWithImageName:NormalImageName];
    
    self.backgroundStarView = [self createStarViewWithImageName:SelectedImageName];
    
    self.foregroundStarView.frame = CGRectMake(0, 0, self.bounds.size.width * _currentScore / self.numberOfStars, self.bounds.size.height);
    
    [self addSubview:self.backgroundStarView];
    
    [self addSubview:self.foregroundStarView];
}

/**
 根据图片名称创建StarView

 @param imageName 图片名称
 */
- (UIView *)createStarViewWithImageName:(NSString *)imageName {
    
    UIView *view = [[UIView alloc] initWithFrame:self.bounds];
    
    view.clipsToBounds = YES;
    
    view.backgroundColor = [UIColor clearColor];
    
    for (NSInteger i = 0; i < self.numberOfStars; i ++) {
        
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
        
        imageView.frame = CGRectMake(i * self.bounds.size.width / self.numberOfStars, 0, self.bounds.size.width / self.numberOfStars, self.bounds.size.height);
        
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        
        [view addSubview:imageView];
    }
    
    return view;
}

/**
 根据偏移量计算最终的评分

 @param realStarScore 真实的偏移量
 */
- (void)handleRealStarScore:(CGFloat)realStarScore {
    
    switch (_rateStyle) {
            
        case XKWholeStarStyle:
            
            if (realStarScore < 0.5) {
                
                self.currentScore = 0;
                
            } else {
                
                self.currentScore = ceilf(realStarScore);
            }
            
            break;
            
        case XKHalfStarStyle:
            
            if (realStarScore < 0.4) {
                
                self.currentScore = 0;
                
            } else {
                
                self.currentScore = roundf(realStarScore) > realStarScore ? ceilf(realStarScore) : (ceilf(realStarScore) - 0.5);
            }
            
            break;
            
        case XKIncompleteStarStyle:
            
            self.currentScore = realStarScore;
            
            break;
            
        default:
            
            break;
    }
}

#pragma mark -- touch事件处理

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [event touchesForView:self];
    
    NSSet *allTouches = [event allTouches];
    
    UITouch *touch = [allTouches anyObject];
    
    CGPoint point = [touch locationInView:[touch view]];
    
    CGFloat offset = point.x;
    
    CGFloat realStarScore = offset / (self.bounds.size.width / self.numberOfStars);
    
    [self handleRealStarScore:realStarScore];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [event touchesForView:self];
    
    NSSet *allTouches = [event allTouches];
    
    UITouch *touch = [allTouches anyObject];
    
    CGPoint point = [touch locationInView:[touch view]];
    
    CGFloat offset = point.x;
    
    CGFloat realStarScore = offset / (self.bounds.size.width / self.numberOfStars);
    
    [self handleRealStarScore:realStarScore];
}

- (void)layoutSubviews {
    
    [super layoutSubviews];
    
    __weak XKStarRateView *weakSelf = self;
    
    CGFloat animationTimeInterval = self.isAnimation ? 0.2 : 0;
    
    [UIView animateWithDuration:animationTimeInterval animations:^{
        
        weakSelf.foregroundStarView.frame = CGRectMake(0, 0, weakSelf.bounds.size.width * weakSelf.currentScore/self.numberOfStars, weakSelf.bounds.size.height);
    }];
}

#pragma mark -- setter方法

- (void)setCurrentScore:(CGFloat)currentScore {
    
    if (_currentScore == currentScore) {
        
        return;
    }
    
    if (currentScore < 0) {
        
        _currentScore = 0;
        
    } else if (currentScore > _numberOfStars) {
        
        _currentScore = _numberOfStars;
        
    } else {
        
        _currentScore = currentScore;
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(starRateView:currentScore:)]) {
        
        [self.delegate starRateView:self currentScore:_currentScore];
    }
    
    if (self.complete) {
        
        _complete(_currentScore);
    }
    
    [self setNeedsLayout];
}

@end

全部的代码都在这里了。同样的,需要的朋友可以点击这里下载Demo工程。如果在使用过程中发现问题欢迎留言提出。谢谢!

特别感谢

在代码封装的过程中有参考这里的代码 在此感谢。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,042评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,943评论 4 60
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,327评论 0 17
  • 昨日,中国首艘国产航母下水的消息在全世界刷屏,堪称巨龙入海,横空出世,举国欢腾,世人瞩目。当然,这是靠强硬的技术实...
    滴水温柔阅读 322评论 0 0
  • 你,我的妞妞,天真活泼的三岁小姑娘。你在我最好的年华出现,让我成为了你的妈妈,我要感谢你,是你,完整了我的人生。...
    玲小梦阅读 522评论 0 2