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

【iOS】0行代码实现评分星星视图_第1张图片
最终效果
要求:
  • Platform: iOS7.0+
  • Language: Objective-C
  • Editor: Xcode6.0+
实现
  • 思路
    UIPogressView + UIImage

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

  • 属性设置


    【iOS】0行代码实现评分星星视图_第2张图片
    属性设置
  • 交互逻辑代码

注意:_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 *)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 *)touches withEvent:(UIEvent *)event{
    [self updateProgressWithTouches:touches isMoved:false];
}

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

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

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

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

github

https://github.com/BackWorld/HYStarView

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

你可能感兴趣的:(【iOS】0行代码实现评分星星视图)