iOS实现支持小数的星星评分组件实例代码

2020-01-21 00:06:24王冬梅

而完成触摸操作时,我们就可以用一个回调将当前的评分传给外界。


@protocol CDZStarsControlDelegate<NSObject>
@optional

/**
 回调星星改变后的分数

 @param starsControl 星星组件
 @param score 分数
 */
- (void)starsControl:(CDZStarsControl *)starsControl didChangeScore:(CGFloat)score;
@end

- (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
 [super endTrackingWithTouch:touch withEvent:event];
 if ([self.delegate respondsToSelector:@selector(starsControl:didChangeScore:)]) {
  [self.delegate starsControl:self didChangeScore:self.score];
 }
}

 

- (void)cancelTrackingWithEvent:(UIEvent *)event {
 [super cancelTrackingWithEvent:event];
 if ([self.delegate respondsToSelector:@selector(starsControl:didChangeScore:)]) {
  [self.delegate starsControl:self didChangeScore:self.score];
 }
}

封装


- (instancetype)initWithFrame:(CGRect)frame
      stars:(NSInteger)number
      starSize:(CGSize)size
    noramlStarImage:(UIImage *)normalImage
   highlightedStarImage:(UIImage *)highlightedImage{
 if (self = [super initWithFrame:frame]) {
  _numberOfStars = number;
  _normalStarImage = normalImage;
  _highlightedStarImage = highlightedImage;
  _starSize = size;
  _allowFraction = NO;
  self.clipsToBounds = YES;
  self.backgroundColor = [UIColor clearColor];
  [self setupView];
 }
 return self;
}

开放score属性和allowFraction属性即可。使用起来也很简单。


 CDZStarsControl *starsControl = [CDZStarsControl.alloc initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, 50) stars:5 starSize:CGSizeMake(50, 50) noramlStarImage:[UIImage imageNamed:@"star_normal"] highlightedStarImage:[UIImage imageNamed:@"star_highlighted"]];
 starsControl.delegate = self;
 starsControl.allowFraction = YES;
 starsControl.score = 2.6f;
 [self.view addSubview:starsControl];

然后在delegate里处理分数改变后的操作即可。

源码下载

所有源码和Demo(本地下载)

可以直接拿文件去使用或修改,也支持Cocoapods.

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对ASPKU的支持。


注:相关教程知识阅读请移步到IOS开发频道。