Is there any controls available for star rating?

谁说胖子不能爱 提交于 2019-12-03 05:54:38

You can check the ASStar rating .

Add the control directly to your view controller or you can add into your cell .

And here is github link.

I recommend HCSStarRatingView. It is native-looking and it also supports IB_DESIGNABLE and IBInspectable.

Take a look, it should suit you just fine:

https://www.cocoacontrols.com/search?utf8=%E2%9C%93&q=star+rating

Note: This is a "DISPLAY ONLY" one.

I took a different approach here, I created a label with attributed string using a font with stars, you can check my category here. I used "SS Pika" font,

#import "NSMutableAttributedString+Stars.h"

@implementation NSMutableAttributedString (Stars)

+ (NSAttributedString *)starWithRating:(CGFloat)rating
                            outOfTotal:(NSInteger)totalNumberOfStars
                          withFontSize:(CGFloat) fontSize{
    UIFont *currentFont = [UIFont fontWithName:@"SS Pika" size:fontSize];
    NSDictionary *activeStarFormat = @{
                                           NSFontAttributeName : currentFont,
                                           NSForegroundColorAttributeName : [UIColor redColor]
                                           };
    NSDictionary *inactiveStarFormat = @{
                                             NSFontAttributeName : currentFont,
                                             NSForegroundColorAttributeName : [UIColor lightGrayColor]
                                             };

    NSMutableAttributedString *starString = [NSMutableAttributedString new];

    for (int i=0; i < totalNumberOfStars; ++i) {
        //Full star
        if (rating >= i+1) {
            [starString appendAttributedString:[[NSAttributedString alloc]
                                               initWithString:@"\u22C6 " attributes:activeStarFormat]];
        }
        //Half star
        else if (rating > i) {
            [starString appendAttributedString:[[NSAttributedString alloc]
                                               initWithString:@"\uE1A1 " attributes:activeStarFormat]];
        }
        // Grey star
        else {
            [starString appendAttributedString:[[NSAttributedString alloc]
                                               initWithString:@"\u22C6 " attributes:inactiveStarFormat]];
        }

    }
    return starString;
}
@end

USAGE:

self.ratingLabel.attributedText = [NSMutableAttributedString starWithRating:rating outOfTotal:5 withFontSize:9.0f];

Here is the SWIFT Version

extension NSMutableAttributedString{

    func starWithRating(rating:Float, outOfTotal totalNumberOfStars:NSInteger, withFontSize size:CGFloat) ->NSAttributedString{


        let currentFont = UIFont(name: "<USE UR FONT HERE>", size: size)!

        let activeStarFormat = [ NSFontAttributeName:currentFont, NSForegroundColorAttributeName: UIColor.redColor()];

        let inactiveStarFormat = [ NSFontAttributeName:currentFont, NSForegroundColorAttributeName: UIColor.lightGrayColor()];

        let starString = NSMutableAttributedString()

        for(var i = 0; i < totalNumberOfStars; ++i){

            if(rating >= Float(i+1)){
                // This is for selected star. Change the unicode value according to the font that you use
                starString.appendAttributedString(NSAttributedString(string: "\u{22C6} ", attributes: activeStarFormat))
            }
            else if (rating > Float(i)){
                // This is for selected star. Change the unicode value according to the font that you use
                starString.appendAttributedString(NSAttributedString(string: "\u{E1A1} ", attributes: activeStarFormat))
            }
            else{
                // This is for de-selected star. Change the unicode value according to the font that you use
                starString.appendAttributedString(NSAttributedString(string: "\u{22C6} ", attributes: inactiveStarFormat))
            }
        }

        return starString
    }
}

USAGE:

starLabel.attributedText = NSMutableAttributedString().starWithRating(3.5, outOfTotal: 5, withFontSize: 8.0)
starLabelFull.attributedText = NSMutableAttributedString().starWithRating(5, outOfTotal: 5, withFontSize: 8.0)
starLabelZero.attributedText = NSMutableAttributedString().starWithRating(0, outOfTotal: 5, withFontSize: 8.0)

Swift3

https://github.com/marketplacer/Cosmos

  • install pod

    target 'TargetName' do

    pod 'Cosmos'

  • Install pod file with this command pod install

  • Put a simple UIView in your storyboard and give the class name as CosmosView and Module name Cosmos

HERE YOU CAN ACCESS THE ATTRIBUTES

Use https://github.com/hugocampossousa/HCSStarRatingView. it easy to implement this. just write down these lines of code. Create IBOutlet HCSStarRatingView for in .h file an create one string for storing the rating value.

@property (weak, nonatomic) IBOutlet HCSStarRatingView *starRatingView;
@property (weak, nonatomic) NSString *ratingStr;

in .m file write down these lines

self.starRatingView.maximumValue = 5;
self.starRatingView.minimumValue = 0;
self.starRatingView.value = 0;
self.starRatingView.tintColor = [UIColor yellowColor];
self.starRatingView.allowsHalfStars = YES;
self.starRatingView.emptyStarImage = [[UIImage imageNamed:@"heart-empty"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
self.starRatingView.filledStarImage = [[UIImage imageNamed:@"heart-full"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
[self.starRatingView addTarget:self action:@selector(didChangeValue:) forControlEvents:UIControlEventValueChanged];

- (IBAction)didChangeValue:(HCSStarRatingView *)sender {
   NSLog(@"Changed rating to %.1f", sender.value);
  ratingStr = [NSString stringWithFormat:@"%.1f",sender.value];
  if([hostRatingStr isEqualToString:@"-0.0"]){
      self.ratingLbl.text = @"0.0";
  }else{
      self.ratingLbl.text = hostRatingStr;
   }
 }

I just wrote this simple UIView subclass that draws stars rating from 0 to 5 including half stars. You can set the color with tintColor property and set the rating in interface editor. View width should be set to 5 * height.

class StarsView: UIView {

    @IBInspectable var rating: Double = 5.0 {
        didSet {
            setNeedsLayout()
        }
    }

    func starPath(size: CGFloat, full: Bool) -> UIBezierPath {
        let fullPoints = [CGPoint(x: 0.5, y: 0.03), CGPoint(x: 0.61, y: 0.38), CGPoint(x: 0.99, y: 0.38), CGPoint(x: 0.68, y: 0.61), CGPoint(x: 0.8, y: 0.97), CGPoint(x: 0.5, y: 0.75), CGPoint(x: 0.2, y: 0.97), CGPoint(x: 0.32, y: 0.61), CGPoint(x: 0.01, y: 0.38), CGPoint(x: 0.39, y: 0.38)].map({ CGPoint(x: $0.x * size, y: $0.y * size) })
        let halfPoints = [CGPoint(x: 0.5, y: 0.03), CGPoint(x: 0.5, y: 0.75), CGPoint(x: 0.2, y: 0.97), CGPoint(x: 0.32, y: 0.61), CGPoint(x: 0.01, y: 0.38), CGPoint(x: 0.39, y: 0.38)].map({ CGPoint(x: $0.x * size, y: $0.y * size) })
        let points = full ? fullPoints : halfPoints
        let starPath = UIBezierPath()
        starPath.move(to: points.last!)
        for point in points {
            starPath.addLine(to: point)
        }
        return starPath
    }

    func starLayer(full: Bool) -> CAShapeLayer {
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = starPath(size: bounds.size.height, full: full).cgPath
        shapeLayer.fillColor = tintColor.cgColor
        return shapeLayer
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        let sublayers = layer.sublayers
        for sublayer in sublayers ?? [] {
            sublayer.removeFromSuperlayer()
        }
        for i in 1...5 {
            if rating >= Double(i) - 0.5 {
                let star = starLayer(full: rating >= Double(i))
                star.transform = CATransform3DMakeTranslation(bounds.size.height * CGFloat(i - 1), 0, 0)
                layer.addSublayer(star)
            }
        }
    }
}

Yeah there are many libraries which you can use to make such controls like cosmos Cosmos library for rating control

if you want something like that looks like rating graph (like the one in image)then you can see this repo in github Rating graph view in iOS

If all you want is whole numbers of stars, you can use a simple String Array and use it to set the text property of a UILabel.

let ratingsDisplay = [
    "★☆☆☆☆",
    "★★☆☆☆",
    "★★★☆☆",
    "★★★★☆",
    "★★★★★"
]

let rating = 4
let label = UILabel()
label.text = ratingsDisplay[rating - 1]

Make sure you set the font of the UILabel to one which displays the black and white stars at the same size. Many but not all do.

Use https://github.com/shantaramk/RatingView.

It effortless to implement this. just follow below steps:

Set Star View IBOutlet

    @IBOutlet weak var rateView: StarRateView!

Prepare Star Rate View

func setupStarRateView() {
    self.rateView.delegate = self
    self.rateView.maxCount = 5
    self.rateView.fillImage = UIImage(named: "fill_star")!
    self.rateView.emptyImage = UIImage(named: "empty_star")!
}

Adopt Rate View Delegate

extension RateServiceViewController: RatingViewDelegate {

func updateRatingFormatValue(_ value: Int) {
    print("Rating : = ", value)
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!