1. 程式人生 > >iOS 一個簡單的實現星級評分的方法

iOS 一個簡單的實現星級評分的方法

我們在開發工程中經常會遇到評分的功能,下面我提供的方法只能用來顯示,暫時不支援點選變化

//
//  StartView.h
//
//  Created by Will han on 16/3/31.
//

#import <UIKit/UIKit.h>

@interface StartView : UIView
{
    CGFloat _starSize;        /* 根據字型大小來確定星星的大小 */
    NSInteger _maxStar;      /* 總共的長度 */
    NSInteger _showStar;    //需要顯示的星星的長度
    UIColor *_emptyColor;   //未點亮時候的顏色
    UIColor *_fullColor;    //點亮的星星的顏色
}
@property (nonatomic, assign) CGFloat starSize;
@property (nonatomic, assign) NSInteger maxStar;
@property (nonatomic, assign) NSInteger showStar;
@property (nonatomic, retain) UIColor *emptyColor;
@property (nonatomic, retain) UIColor *fullColor;

@end

//
//  StartView.m
//  MeiMeiDu
//
//  Created by Will han on 16/3/31.

//

#import "StartView.h"

@implementation StartView
@synthesize starSize = _starSize;
@synthesize maxStar = _maxStar;
@synthesize showStar = _showStar;
@synthesize emptyColor = _emptyColor;
@synthesize fullColor = _fullColor;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.backgroundColor = [UIColor clearColor];
        //預設的星星的大小是 13.0f
        self.starSize = 13.0f;
        //未點亮時的顏色是 灰色的
        self.emptyColor = [UIColor colorWithRed:167.0f / 255.0f green:167.0f / 255.0f blue:167.0f / 255.0f alpha:1.0f];
        //點亮時的顏色是 亮黃色的
        self.fullColor = [UIColor colorWithRed:255.0f / 255.0f green:121.0f / 255.0f blue:22.0f / 255.0f alpha:1.0f];
        //預設的長度設定為100
        self.maxStar = 100;
    }
    
    return self;
}

//重繪檢視
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    NSString* stars = @"★★★★★";
    
    rect = self.bounds;
    UIFont *font = [UIFont boldSystemFontOfSize:_starSize];
    CGSize starSize = [stars sizeWithFont:font];
    rect.size=starSize;
    [_emptyColor set];
    [stars drawInRect:rect withFont:font];
    
    CGRect clip = rect;
    clip.size.width = clip.size.width * _showStar / _maxStar;
    CGContextClipToRect(context,clip);
    [_fullColor set];
    [stars drawInRect:rect withFont:font];
    self.backgroundColor = [UIColor greenColor];
}


@end
下面是呼叫方法
 StartView *myStartView = [[StartView alloc]initWithFrame:CGRectMake(0, 0, 217, 21)];
    myStartView.showStar = 4.2*20;
    [cell.startView  addSubview:myStartView]; //評論是4.2分的

效果圖: