iOS自定义实现星级评分功能控件

最近项目需要实现X宝,X东上面的的收货物品的星级评价功能,首先当然是搜索大法了,找了两三个初看还可以的,体验了下,结果就是用是能用,但是有些细节上还是不太符合自己的需求。我这要达到的功能是:
1、能实现整颗星、半颗星的显示。需求要求点评的时候是只能选择整颗星,展示的时候可以显示到半颗星。
2、能拖动、能点击显示。
3、其他细节。
最终还是在WTKStarView的参考上自己实现了一个星级评分。



这里说下本控件的功能:
1、支持整颗星、半颗星的显示,包括2.3、3.6这样的。
2、支持拖动、点击。
3、支持设置一颗星星的Size,星星之间的间距。
4、支持先初始化,在传Frame布局。

下面上代码示范:
先看看整体的代码.h

#import <UIKit/UIKit.h>

@class ABStarLevelView;

typedef NS_ENUM(NSInteger, ABStarLevelType) {
    ABStarLevelTypeFull = 0, //满星
    ABStarLevelTypeHalf, //半星
};

@interface ABStarLevelStyle : NSObject
/**
 类型(默认是满星)
 */
@property (nonatomic, assign) ABStarLevelType starType;
/**
 亮起的星星图片名字
 */
@property (nonatomic, copy) NSString *highlightStarImageName;
/**
 暗的星星图片名字
 */
@property (nonatomic, copy) NSString *normalStarImageName;
/**
 星星大小(默认CGSizeZero)
 */
@property (nonatomic, assign) CGSize starSize;
/**
 星星间距(默认0,即根据给的宽度来划分)
 */
@property (nonatomic, assign) CGFloat starInterval;

@end

@protocol ABStarLevelViewDelegate <NSObject>
@optional
- (void)starLevelView:(ABStarLevelView *)starLevelView currentStarLevel:(CGFloat)currentStarLevel;
@end

@interface ABStarLevelView : UIView

/**
 星级 0-5(默认0星)
 */
@property (nonatomic, assign) CGFloat starLevel;
/**
 是否允许交互(拖动、点击)
 */
@property (nonatomic, assign) BOOL touchEnabled;
/**
 当前设置的星级
 */
@property (nonatomic, assign, readonly) CGFloat currentSatrLevel;

@property (nonatomic, weak) id<ABStarLevelViewDelegate>delegate;

/**
 初始化StarLevel

 @param style 允许传nil(传nil,内部默认初始化一个ABStarLevelStyle)
 @return ABStarLevelView
 */
- (instancetype)initWithStyle:(ABStarLevelStyle *)style;

/**
 初始化StarLevel

 @param frame 设置大小
 @param style 允许传nil(传nil,内部默认初始化一个ABStarLevelStyle)
 @return ABStarLevelView
 */
- (instancetype)initWithFrame:(CGRect)frame style:(ABStarLevelStyle *)style;

@end

再来看看使用例子

    //默认样式
    ABStarLevelStyle *style = [[ABStarLevelStyle alloc]init];
    
    ABStarLevelView *starLevelView = [[ABStarLevelView alloc]initWithFrame:CGRectMake(30, 250, 210, 30) style:style];
    starLevelView.delegate = self;
    starLevelView.backgroundColor = [UIColor greenColor];
    starLevelView.touchEnabled = YES;
    [self.view addSubview:starLevelView];
    self.starLevelView = starLevelView;
    
    //设置星星大小,间距
    ABStarLevelStyle *style2 = [[ABStarLevelStyle alloc]init];
    style2.starType = ABStarLevelTypeFull;//ABStarLevelTypeHalf(半星)
    style2.starSize = CGSizeMake(30, 30);
    style2.starInterval = 15;
    
    ABStarLevelView *starLevelView2 = [[ABStarLevelView alloc]initWithFrame:CGRectMake(30, 350, 210, 30) style:style2];
    starLevelView2.delegate = self;
    starLevelView2.backgroundColor = [UIColor greenColor];
    starLevelView2.touchEnabled = YES;
    [self.view addSubview:starLevelView2];
-(void)starLevelView:(ABStarLevelView *)starLevelView currentStarLevel:(CGFloat)currentStarLevel
{
    NSLog(@"FFFFF === %f",currentStarLevel);
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"currentSatrLevel == %f",self.starLevelView.currentSatrLevel);
}

最后贴上.m文件

#import "ABStarLevelView.h"

#define STAR_NUM 5

@implementation ABStarLevelStyle

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.starType = ABStarLevelTypeFull;
        self.starInterval = 0;
        self.starSize = CGSizeZero;
        self.normalStarImageName = @"start_normal";
        self.highlightStarImageName = @"start_highlight";
    }
    return self;
}

@end


@interface ABStarLevelView ()

@property (nonatomic, strong) ABStarLevelStyle *style;

@property (nonatomic, strong) NSMutableArray *frontStars;

@property (nonatomic, strong) NSMutableArray *backStars;

@property (nonatomic, strong) UIView *frontView;

@property (nonatomic, strong) UIView *backView;

@property (nonatomic, assign) CGFloat starWidth;

@property (nonatomic, assign) CGFloat starHeight;

@end

@implementation ABStarLevelView

-(NSMutableArray *)frontStars
{
    if (_frontStars == nil) {
        _frontStars = [NSMutableArray arrayWithCapacity:STAR_NUM];
    }
    return _frontStars;
}

-(NSMutableArray *)backStars
{
    if (_backStars == nil) {
        _backStars = [NSMutableArray arrayWithCapacity:STAR_NUM];
    }
    return _backStars;
}

- (instancetype)initWithStyle:(ABStarLevelStyle *)style
{
    self = [super init];
    if (self) {
        if (style == nil) {
            style = [[ABStarLevelStyle alloc]init];
        }
        self.style = style;
        [self addTheView];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame style:(ABStarLevelStyle *)style
{
    self = [super initWithFrame:frame];
    if (self) {
        if (style == nil) {
            style = [[ABStarLevelStyle alloc]init];
        }
        self.style = style;
        [self addTheView];
    }
    return self;
}

- (void)addTheView
{
    self.touchEnabled = NO;
    if (self.style.starType == ABStarLevelTypeFull) {
        for (NSInteger i = 0; i < STAR_NUM; i ++) {
            UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:self.style.highlightStarImageName]];
            [self addSubview:imageView];
            [self.frontStars addObject:imageView];
        }
    }
    else {
        self.backView = [self creatViewWithImageName:self.style.normalStarImageName front:NO];
        [self addSubview:self.backView];
        self.frontView = [self creatViewWithImageName:self.style.highlightStarImageName front:YES];
        [self addSubview:self.frontView];
    }
}

- (UIView *)creatViewWithImageName:(NSString *)imageName front:(BOOL)front
{
    UIView *view = [[UIView alloc]init];
    view.layer.masksToBounds = YES;
    view.backgroundColor = [UIColor clearColor];
    for (NSInteger i = 0; i < STAR_NUM; i ++) {
        UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:imageName]];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        [view addSubview:imageView];
        front ? [self.frontStars addObject:imageView] : [self.backStars addObject:imageView];
    }
    return view;
}

-(void)layoutSubviews
{
    [super layoutSubviews];

    CGFloat starWidth = 0;
    CGFloat starHeight = 0;
    
    CGFloat parentViewWidth = self.frame.size.width;
    CGFloat parentViewHeight = self.frame.size.height;
    
    if (self.style.starSize.width == 0 || self.style.starSize.width > parentViewWidth / 5.0) {
        starWidth = parentViewWidth / 8.0;
        if (starWidth > parentViewHeight) {
            starWidth = parentViewHeight;
        }
        starHeight = starWidth;
    }
    else {
        starWidth = self.style.starSize.width;
        if (starWidth > parentViewHeight) {
            starWidth = parentViewHeight;
        }
        starHeight = self.style.starSize.height > parentViewHeight ? starWidth : self.style.starSize.height;
    }
    
    if (self.style.starInterval <= 0) {
        self.style.starInterval = (parentViewWidth - starWidth * 5.0) / 4.0;
    }
    
    CGFloat starViewY = (parentViewHeight - starHeight) / 2;
    
    self.starWidth = starWidth;
    self.starHeight = starHeight;
    
    if (self.style.starType == ABStarLevelTypeFull) {
        for (NSInteger i = 0; i < STAR_NUM; i ++) {
            UIImageView *imageView = self.frontStars[i];
            imageView.frame = CGRectMake(i * (starWidth + self.style.starInterval), starViewY, starWidth, starHeight);
        }
    }
    else {
        self.frontView.frame = self.bounds;
        self.backView.frame = self.bounds;
        for (NSInteger i = 0; i < STAR_NUM; i ++) {
            CGRect frame = CGRectMake(i * (starWidth + self.style.starInterval), starViewY, starWidth, starHeight);
            
            UIImageView *fontImageView = self.frontStars[i];
            fontImageView.frame = frame;
            
            UIImageView *backImageView = self.backStars[i];
            backImageView.frame = frame;
        }
    }
    
    //给个初始值
    self.starLevel = self.starLevel;
}

-(void)setStarLevel:(CGFloat)starLevel
{
    starLevel = MAX(0, MIN(5.0, starLevel));
    _starLevel = starLevel;
    
    if (self.style.starType == ABStarLevelTypeFull) {
        [self.frontStars enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            UIImageView *imageView = obj;
            if (idx + 1 <= starLevel) {
                imageView.image = [UIImage imageNamed:self.style.highlightStarImageName];
            }
            else {
                imageView.image = [UIImage imageNamed:self.style.normalStarImageName];
            }
        }];
    }
    else {
        int value = starLevel;
        CGFloat width = (value) * (self.starWidth + self.style.starInterval) + (starLevel - value) * self.starWidth;
        self.frontView.frame = CGRectMake(0, 0, width, self.frame.size.height);
    }
    
    _currentSatrLevel = starLevel;
}

#pragma mark - touch
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (!self.touchEnabled) {
        return;
    }
    
    if (self.style.starType == ABStarLevelTypeFull) {
        [self resetFullStar:touches];
    }
    else {
        [self resetHalfStar:touches];
    }
}

-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (!self.touchEnabled) {
        return;
    }
    
    if (self.style.starType == ABStarLevelTypeFull) {
        [self resetFullStar:touches];
    }
    else {
        [self resetHalfStar:touches];
    }
}

- (void)resetFullStar:(NSSet<UITouch *> *)touches
{
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self];
    
    CGFloat starLevel = 0;
    
    for (NSInteger i = 0; i < STAR_NUM; i++) {
        UIImageView *imageView = self.frontStars[i];
        if (touchPoint.x >= 0 && touchPoint.x < self.frame.size.width && touchPoint.y >= 0 && touchPoint.y < self.frame.size.height) { //触摸点在星星上
            if (imageView.frame.origin.x > touchPoint.x) {
                imageView.image = [UIImage imageNamed:self.style.normalStarImageName];
            }
            else {
                imageView.image = [UIImage imageNamed:self.style.highlightStarImageName];
                starLevel ++;
            }
        }
    }
    
    _currentSatrLevel = starLevel;
    if (self.delegate && [self.delegate respondsToSelector:@selector(starLevelView:currentStarLevel:)]) {
        [self.delegate starLevelView:self currentStarLevel:starLevel];
    }
}

- (void)resetHalfStar:(NSSet<UITouch *> *)touches
{
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self];
    
    CGPoint starPoint;
    CGFloat starLevel = 0;
    int flag = 0;//判断是否已经调用delegate
    
    if (touchPoint.x >= 0 && touchPoint.x < self.frame.size.width && touchPoint.y >= 0 && touchPoint.y < self.frame.size.height) {
        for (NSInteger i = 0; i < STAR_NUM; i ++) {
            UIImageView *imageView = self.frontStars[i];
            starPoint = [touch locationInView:imageView];
            if (starPoint.x >= 0 && starPoint.x <= self.starWidth) { //触摸点在星星上
                CGFloat value = starPoint.x / self.starWidth;
                self.frontView.frame = CGRectMake(0, 0, imageView.frame.origin.x + value * self.starWidth, self.frame.size.height);
                
                _currentSatrLevel = i + value;
                if (flag == 0 && self.delegate && [self.delegate respondsToSelector:@selector(starLevelView:currentStarLevel:)]) {
                    [self.delegate starLevelView:self currentStarLevel:i + value];
                }
                flag ++;
            }
            else {
                self.frontView.frame = CGRectMake(0, 0, touchPoint.x, self.frame.size.height);
                if (touchPoint.x > imageView.frame.origin.x) {
                    starLevel = i + 1;
                    _currentSatrLevel = starLevel;
                }
            }
        }
        if (flag == 0 && self.delegate && [self.delegate respondsToSelector:@selector(starLevelView:currentStarLevel:)]) {
            [self.delegate starLevelView:self currentStarLevel:starLevel];
        }
    }
}

@end

基本上就这样,感觉还有很多细节可以优化!

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

推荐阅读更多精彩内容