评分控件

字数 92阅读 131

现在很多应用都有评分功能.实现步骤


  1. 创建足够的 imageView, 用来改变图片.
  2. 通过手势来区分点击到的位置.
  3. 通过位置判断 imageView 显示的图片

#import "DZScoreView.h"

@implementation DZScoreView

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.maxScore = 5;
        [self setupGestureRecognizer];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.maxScore = 5;
        [self setupGestureRecognizer];
    }
    return self;
}

- (void)setupUI {
    for (int i = 0; i < self.maxScore; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"back"]];
        [self addSubview:imageView];
    }
}

- (void)setupGestureRecognizer {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
    [self addGestureRecognizer:tap];
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panClick:)];
    [self addGestureRecognizer:pan];
}

- (void)tapClick:(UITapGestureRecognizer *)tap {
    [self changeScoreFromGestureRecognizer:tap];
}

// 会频繁调用
- (void)panClick:(UIPanGestureRecognizer *)pan {
    [self changeScoreFromGestureRecognizer:pan];
}

- (void)changeScoreFromGestureRecognizer:(UIGestureRecognizer *)recognize {
    CGPoint point = [recognize locationInView:self];
    
    for (UIImageView *imageView in self.subviews) {
        if (CGRectGetMinX(imageView.frame) < point.x) {
            imageView.image = [UIImage imageNamed:@"fore"];
        } else {
            imageView.image = [UIImage imageNamed:@"back"];
        }
    }
}

- (void)layoutSubviews {
    CGFloat w = self.width / self.maxScore;
    CGFloat h = w;
    
    for (int i = 0; i < self.subviews.count; i++) {
        UIImageView *imgView = self.subviews[i];
        imgView.frame = CGRectMake(i * w , 0, w, h);
    }
}

- (void)setMaxScore:(NSInteger)maxScore {
    _maxScore = maxScore;

    if (self.subviews) {
        for (UIImageView *imgView in self.subviews) {
            [imgView removeFromSuperview];
        }
//       这种判断方式可以
//        for (NSInteger i = self.subviews.count - 1; i >= 0; i--) {
//            UIImageView *imageView = self.subviews[i];
//            [imageView removeFromSuperview];
//        }
//        
//        注意:这种判断方式,会导致不能完全删除只能删除一半
//        for (NSInteger i = 0; i < self.subviews.count; i--) {
//            UIImageView *imageView = self.subviews[i];
//            [imageView removeFromSuperview];
//        }
           
    }

    [self setupUI];
}

@end

在这里我定义了一个最大的评分的属性maxScore如果不设置的话默认会是5.当然现在一般都是5.

推荐阅读更多精彩内容