ios 星星评分(支持点击和滑动)

思路:ios 中 touchesBegan和touchesMoved两个方法可以获取到UIView上的点击的坐标和滑动的坐标,根据坐标,位于X坐标左边的imageview设置为“button_star_red”,右边的设置为“button_star_red”。

第一步:在UIViewController上添加一个UIView(两种方式,直接拖拽或者在”.m”文件代码创建,这里直接拖拽)命名为:myview,width 为星星宽度的6倍(总共5颗星星,确保可以0分),heigh为星星的高度

1
@property (weak, nonatomic) IBOutlet UIView *myview;

第二步:在myview上添加imageview,将星星初始化为“button_star_white”,并且按顺序加入到数组中,便于后期遍历改变星星颜色,代码如下:

1
2
3
4
5
6
7
UIImageView *imageView;
    for (int i = 0; i < 5; i++) {
        imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"button_star_white"]];
        imageView.frame = CGRectMake(_myview.bounds.origin.x+((i+1)*24), _myview.bounds.origin.y, 24, 24);
        [_myview addSubview:imageView];
        [_allStar addObject:imageView];
    }

第三步:获取点击活着滑动的坐标,根据坐标,将坐标X以左的星星置为“button_star_white”(星星的宽和高都是24,)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#pragma mark - 点击的坐标
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:_myview];
    UIImageView *im ;
    for(int i = 0;i < 5 ; i++){
        im = _allStar[i];
        NSLog(@"_all[%i] = (%f,%f)",i,im.frame.origin.x,im.frame.origin.y);
        if ((touchPoint.x > 0)&&(touchPoint.x < 144)&&(touchPoint.y > 0)&&(touchPoint.y < 24)) {
            NSString *myscore = [NSString stringWithFormat:@"分数为:%i",((int)touchPoint.x)/24];
            _score.text = myscore;//_score是一个UILable,myscore为分数,显示在给用户看,关于这个不在赘述
            if (im.frame.origin.x > touchPoint.x) {
                im.image =[UIImage imageNamed:@"button_star_white"];
            }else{
                im.image =[UIImage imageNamed:@"button_star_red"];
            }
        }
    }
}
#pragma mark - 滑动的坐标
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:_myview];
    UIImageView *im ;
    for(int i = 0;i < 5 ; i++){
        im = _allStar[i];
        NSLog(@"_all[%i] = (%f,%f)",i,im.frame.origin.x,im.frame.origin.y);
        if ((touchPoint.x > 0)&&(touchPoint.x < 144)&&(touchPoint.y > 0)&&(touchPoint.y < 24)) {
            NSString *myscore = [NSString stringWithFormat:@"分数为:%i",((int)touchPoint.x)/24];
            _score.text = myscore;//_score是一个UILable,myscore为分数,显示在给用户看,关于这个不在赘述
            if (im.frame.origin.x > touchPoint.x) {
                im.image =[UIImage imageNamed:@"button_star_white"];
            }else{
                im.image =[UIImage imageNamed:@"button_star_red"];
            }
        }
    }
}


附上星星图片,三种尺寸button_star_red button_star_red@2x button_star_red@3x button_star_white button_star_white@2x button_star_white@3x


展开阅读全文

没有更多推荐了,返回首页