【iOS】0行代码实现评分星星视图

最终效果
要求:
  • Platform: iOS7.0+
  • Language: Objective-C
  • Editor: Xcode6.0+
实现
  • 思路
    UIPogressView + UIImage

总得来说,就利用progressView的两个属性:_progressImage【顶图】和_trackImage【底图】实现不同进度值下的评分效果。

  • 属性设置


    属性设置
  • 交互逻辑代码

注意:_stepValue是指滑动过程中的最小步进值,0.5表示半颗星,1表示一颗星,要求0 < _stepValue <= 1。

-(void)setProgressImage:(UIImage *)progressImage{
    super.progressImage = [self configureImage:progressImage];
}

-(void)setTrackImage:(UIImage *)trackImage{
    super.trackImage = [self configureImage: trackImage];
}

// 重新计算设置图,使其符合平铺要求
- (UIImage*)configureImage:(UIImage*)image
{
    CGFloat width = self.bounds.size.width / 5;
    CGSize size = CGSizeMake(width, width);
    
    UIGraphicsBeginImageContextWithOptions(size, false, image.scale);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return [newImage resizableImageWithCapInsets:UIEdgeInsetsZero resizingMode:UIImageResizingModeTile];
}

// 设置progressView的进度
-(void)updateProgressWithTouches: (NSSet<UITouch *> *)touches isMoved: (BOOL)isMoved{
    UITouch *touch = touches.anyObject;
    CGPoint loc = [touch locationInView:_progressView];
    
    float value = loc.x / _progressView.bounds.size.width;
    if (value < 0) {
        return;
    }
    float progress = (_stepValue == 0) ? value : ceil(value * 5 / _stepValue) * _stepValue / 5;
    progress = MIN(progress, 1);

    _progressView.progress = progress;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self updateProgressWithTouches:touches isMoved:false];
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self updateProgressWithTouches:touches isMoved:false];
}

-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self updateProgressWithTouches:touches isMoved:true];
}

-(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self updateProgressWithTouches:touches isMoved:false];
}
  • 注意

在设置NSLayout时,设置progressView的高度要和icon_star保持一致,宽度为图片的倍数值,否则会显示错乱。

github

https://github.com/BackWorld/HYStarView

本文只是给读者展示了一种独特的最简单的实现方式,如果对你有帮助,别忘了点个❤️哦。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,511评论 25 709
  • 孙少安和润叶之间的爱情,是最让人纠结的,它是小说中的第一个亮点(越往后就会发现小说中的亮点越多)。对于高小毕业的少...
    舞年horace阅读 13,581评论 4 5
  • 今天读了一篇文章,文章的名字叫做《啥叫幸福?》在这篇文章里中,作者认为: “你病,有人照顾你,这就是幸...
    蒹葭essay阅读 1,677评论 0 3
  • 冰的河 潺潺流淌 无风无波 不语 沉默 火之舞 热烈 蓬勃 活力四射 冰河一瞥 心潮澎湃 不可扼 日日思 夜夜琢磨...
    昂格伦阅读 1,709评论 0 5
  • 表达式 变量或(和)常量和运算符(又叫操作符)的组合叫表达式。表达式中的变量或常量称为操作数,表达式可分为多种类别...
    勇赴阅读 5,089评论 0 1