iOS评分星星允许半颗

你的喜欢是我的坚持的动力!

如图:就这种
Paste_Image.png

思路是黑星是背景,黄星在上边,根据分数来改变黄星的frame,上代码,.花费不小的精力,算是为这种需求提供些新思路,也许对大家有用,有用就点赞谢谢.不多说了

.m如下


#import "ZCStar.h"
#define FOREGROUND_STAR_IMAGE_NAME @"b27_icon_star_yellow"
#define BACKGROUND_STAR_IMAGE_NAME @"b27_icon_star_gray"
#define DEFALUT_STAR_NUMBER 5
@interface ZCStar   ()
@property (nonatomic, strong) UIView *foregroundStarView;
@property (nonatomic, strong) UIView *backgroundStarView;
@property (nonatomic, assign) NSInteger numberOfStars;
@end
@implementation ZCStar

- (instancetype)initWithFrame:(CGRect)frame
{
    return [self initWithFrame:frame numberOfStars:DEFALUT_STAR_NUMBER];
}
- (instancetype)initWithFrame:(CGRect)frame numberOfStars:(NSInteger)numberOfStar
{
    if (self = [super initWithFrame:frame]) {
        _numberOfStars = numberOfStar;
        [self buildDataAndUI];
    }
    return self;
}
- (void)buildDataAndUI
{
    _scorePercent = 1;
    self.foregroundStarView = [self createStarViewWithImage:FOREGROUND_STAR_IMAGE_NAME];
    self.backgroundStarView = [self createStarViewWithImage:BACKGROUND_STAR_IMAGE_NAME];
    
    [self addSubview:self.backgroundStarView];
    [self addSubview:self.foregroundStarView];
}
- (UIView *)createStarViewWithImage:(NSString *)imageName
{
    UIView *view = [[UIView alloc] initWithFrame:self.bounds];
    view.clipsToBounds = YES;
    view.backgroundColor = [UIColor clearColor];
    for (int i = 0; i < self.numberOfStars; i++) {
        UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
        imgView.frame = CGRectMake(i * self.bounds.size.width / self.numberOfStars, 0, self.bounds.size.width / self.numberOfStars, self.bounds.size.height );
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        [view addSubview:imgView];
    }
    return view;
}
- (void)setScorePercent:(CGFloat)scorePercent
{
    if (_scorePercent == scorePercent) {
        return;
    }
    if (scorePercent < 0) {
        _scorePercent = 0;
        
    } else if (scorePercent > 1) {
        _scorePercent = 1;
    } else {
        _scorePercent = scorePercent;
    }
     self.foregroundStarView.frame = CGRectMake(0,0,self.bounds.size.width * self.scorePercent , self.bounds.size.height);
}

.h如下

@interface ZCStar : UIView
@property (nonatomic, assign)CGFloat scorePercent;//0到1,评分

- (instancetype)initWithFrame:(CGRect)frame numberOfStars:(NSInteger)numberOfStar;
@end

如何使用呢?一句话

 ZCStar *view = [[ZCStar alloc] initWithFrame:CGRectMake(100, 100, 200, 100) numberOfStars:5];//星星个数
    [self.view addSubview:view];
    view.scorePercent = 0.48;//评分0 到1 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容