Search code examples
swiftuiviewcocoapodsrating

Swift how to show rating value in star rating


I am trying to show the average rating value in the HCSStarRatingView from cocoa pods. I have a method that figures out the average and now i want pass the average Double to display the correct star rating in Todays Rating. I was wondering how can i do this? Todays Star Rating

Here is the rating average

  class RatingTableViewCell: UITableViewCell {

@IBOutlet weak var dateLabel: UILabel!
var dateValue = Date()
var pastRating: Double = 0.0
@IBInspectable weak var rating: HCSStarRatingView!

var review: Workout?{
    didSet{
        configureCell()
    }
}
func configureCell(){
    if let review = review{
        review.appointment?.scheduled = dateValue
        let formatter = DateFormatter()
        formatter.dateFormat = "mm-dd-YYYY"
        let formattedDate = formatter.string(from: dateValue)
        dateLabel.text = formattedDate
        pastRating = 0.0
    }
}
override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

}

and here is the table view

 func numberOfSections(in tableView: UITableView) -> Int {
    return 30
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    guard let sections = fetchedResultsController.sections else {
        fatalError("No sections in fetchedResultsController")
    }
    return sections.count
}


func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let dequeuedCell = tableView.dequeueReusableCell(withIdentifier: "RatingTableViewCell", for: indexPath);
        guard let cell = dequeuedCell as? RatingTableViewCell else {
            return dequeuedCell
    }
    cell.review = self.fetchedResultsController.object(at: indexPath)

    return cell
}

Solution

  • I have seen HCSStarRatingView, there are property given to display accurate rating. So change you code:

    if let review = review{
        review.appointment?.scheduled = dateValue
        let formatter = DateFormatter()
        formatter.dateFormat = "mm-dd-YYYY"
        let formattedDate = formatter.string(from: dateValue)
        dateLabel.text = formattedDate
    
        // You need to change code like this.
        rating.accurateHalfStars = true
        rating.value = <YourAverageRating>
    
        pastRating = 0.0    // I don't know about this, So can maintain it.
    }
    

    I hope this will help you.