OC_星星评分的实现

374 阅读1分钟

在众多的app中,或多或少都会用到星星评分这样的小功能,特别是电商类

/** 重写属性level的方法,一旦给此属性赋值,就创建星星 @param level 评级分数 */

 -(void)setLevel:(CGFloat)level{
   _level = level;
//    满星
   NSInteger fullStarNumber = (NSInteger)level;
   for (NSInteger i = 0; i < fullStarNumber; i++) {
       [self createStartViewWithImageName:@"full_star" andWithStarPosition:i];
   }
//    半星
   if ((level - fullStarNumber) > 0) {
       [self createStartViewWithImageName:@"half_star" andWithStarPosition:fullStarNumber];
       fullStarNumber++;
   }
//    空星
   for (NSInteger i = fullStarNumber; i < STAR_AMOUNT_NUMBER; i++) {
       [self createStartViewWithImageName:@"empty_star" andWithStarPosition:i];
   }
}

/** 根据图片的名称,以及相应的个数,创建星星的图层 @param imageName 星星图片的名称:全星、半星、空星 @param starNumber 对应星星类型的位置 */

-(void)createStartViewWithImageName:(NSString *)imageName andWithStarPosition:(NSInteger)starPosition{
   UIImageView *imageView = nil;
//    如果发现星星已经创建了,就不要再创建了,重新给图片就可以了
   if (self.subviews.count == STAR_AMOUNT_NUMBER) {
       imageView = self.subviews[starPosition];
       imageView.image = [UIImage imageNamed:imageName];
       return ;
   }
   imageView = [[UIImageView alloc]init];
   imageView.image = [UIImage imageNamed:imageName];
   [imageView sizeToFit];
   imageView.frame = CGRectOffset(imageView.bounds, starPosition * imageView.bounds.size.width, 0);
   [self addSubview:imageView];
}