0

I wanna make a Star Rating for a Job Performance Survey using UITableView and Cosmos. My Problem is, that I have absolutely no clue, how I can access and store the rating, the user is giving for each row.

Maybe someone could help me! :) This is what I have so far... I tried so many different possibilities but always failed massively. I set the initial Rating of the Items to 0, which then should get updated as soon as a user rates it and gets ultimately stored afterwards in Firebase completely when the user presses "save"

import UIKit
import Cosmos
import TinyConstraints

protocol ClassTeamMemberRatingTableViewCelle {
func sharePressed(cell: TeamMemberRatingTableViewCell)
   func ratingDidChange(rating: Float)
}

public class TeamMemberRatingTableViewCell: UITableViewCell {

    @IBOutlet weak var itemLabel: UILabel!
    @IBOutlet weak var cosmos: CosmosView!

    var id: Int = 0

     func update(_ rating: Double, id: Int) {
       cosmos.rating = rating
       self.id = id

        cosmos.didFinishTouchingCosmos = { [weak self] rating in
         print(self?.id) // Access property here
       }
    }


    override public func prepareForReuse() {
      // Ensures the reused cosmos view is as good as new
      cosmos.prepareForReuse()
    }


    public override func awakeFromNib() {
           super.awakeFromNib()


    }

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

          // Configure the view for the selected state
      }

    }

import UIKit
import FirebaseAuth
import FirebaseDatabase
import Cosmos
import TinyConstraints

class TeamMemberRatingViewController: UIViewController {


// MARK: - Properties

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var errorLabel: UILabel!





    var ratingItems: [RatingItem] = []
    var givenStars: Int = 0
    var userID:String?





    override func viewDidLoad() {
        super.viewDidLoad()

      ratingItems = createArray()
        setUpElements()


        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")



      }




    // MARK: - Element Style
    func setUpElements() {


         // Hide the error label
         errorLabel.alpha = 0

    }


    func configureTableView() {
        // remove separators for empty cells
       tableView.tableFooterView = UIView()
        // remove separators from cells
        tableView.separatorStyle = .none
    }

    // Error Handling for save
    func showError(_ message:String) {

        errorLabel.text = message
        errorLabel.alpha = 1
       }

    func createArray() -> [RatingItem] {
        var tempItems: [RatingItem] = []

        let item1 = RatingItem(item: "Ability", rating: 0)
        let item2 = RatingItem(item: "Accuracy", rating: 0)
        let item3 = RatingItem(item: "Planning", rating: 0)
        let item4 = RatingItem(item: "Quality of Work", rating: 0)
        let item5 = RatingItem(item: "Productivity", rating: 0)
        let item6 = RatingItem(item: "Punctuality", rating: 0)
        let item7 = RatingItem(item: "Responsibility", rating: 0)
        let item8 = RatingItem(item: "Job Knowledge", rating: 0)
        let item9 = RatingItem(item: "Creativity", rating: 0)
        let item10 = RatingItem(item: "Initiative", rating: 0)
        let item11 = RatingItem(item: "Job Commitment", rating: 0)
        let item12 = RatingItem(item: "Organization Loyalty", rating: 0)
        let item13 = RatingItem(item: "Supervisor Loyalty", rating: 0)
        let item14 = RatingItem(item: "Dependability", rating: 0)
        let item15 = RatingItem(item: "Honesty", rating: 0)
        let item16 = RatingItem(item: "Cooperation", rating: 0)
        let item17 = RatingItem(item: "Attitude", rating: 0)
        let item18 = RatingItem(item: "Communication Skilss", rating: 0)
        let item19 = RatingItem(item: "Judgment", rating: 0)
        let item20 = RatingItem(item: "Interpersonal Relationship", rating: 0)

        tempItems.append(item1!)
        tempItems.append(item2!)
        tempItems.append(item3!)
        tempItems.append(item4!)
        tempItems.append(item5!)
        tempItems.append(item6!)
        tempItems.append(item7!)
        tempItems.append(item8!)
        tempItems.append(item9!)
        tempItems.append(item10!)
        tempItems.append(item11!)
        tempItems.append(item12!)
        tempItems.append(item13!)
        tempItems.append(item14!)
        tempItems.append(item15!)
        tempItems.append(item16!)
        tempItems.append(item17!)
        tempItems.append(item18!)
        tempItems.append(item19!)
        tempItems.append(item20!)

        return tempItems

    }

    func validateFields() -> String? {

        return nil
    }



    @IBAction func saveRating(_ sender: Any) {

               let user = Auth.auth().currentUser
               if  let user = user {

                   let uid = user.uid
                   userID = uid

                   // Validate the fields
                   let error = validateFields()

                   if error != nil {

                       // There is something wrong with the fields, show error message
                       showError(error!)
                   } else {



//                    PostService.createProject(forprojectTitle: projectTitle)

                   }

               } else { self.showError("Please log out and log in again")}
        }


}



// MARK: - Extension

extension TeamMemberRatingViewController: UITableViewDataSource {


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return ratingItems.count
    }


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

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let ratingItemT = ratingItems[indexPath.row]



       }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        // Fetches the appropriate meal for the data source layout.
        let ratingItemT = ratingItems[indexPath.row]


        let cell = tableView.dequeueReusableCell(withIdentifier: "TeamMemberRatingTableViewCell", for: indexPath) as! TeamMemberRatingTableViewCell


        cell.itemLabel.text = ratingItemT.item

        return cell
    }

}
// MARK: - UITableViewDelegate

extension TeamMemberRatingViewController: UITableViewDelegate {

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
     return 80
    }
}


import Foundation
import UIKit
import FirebaseDatabase.FIRDataSnapshot

class RatingItem {

    var key: String?

    var item: String
    var rating: Int

    init?(item: String, rating: Int) {

            // Initialization should fail if there is no name or if the rating is negative.
            // The name must not be empty
            guard !item.isEmpty else {
                return nil
            }

            // The rating must be between 0 and 5 inclusively
            guard (rating >= 0) && (rating <= 7) else {
                return nil
            }

            // Initialize stored properties.
            self.item = item
            self.rating = rating

        }
    var dictValue: [String: Any] {
        let createdAgo = kSecAttrCreationDate

        return ["Rating_Item" : item,
                "Rating_rating": rating,
                "created_ago": createdAgo]
    }
    init?(snapshot: DataSnapshot) {
        guard let dict = snapshot.value as? [String: Any],
        let item = dict["Rating_Item"] as? String,
        let rating = dict["Rating_rating"] as? Int

            else {return nil}

        self.key = snapshot.key
        self.item = item
        self.rating = rating

    }

}

This is how it looks like:

Table View

Schaedel420
  • 175
  • 11

1 Answers1

0

I would start with your protocol and change it to the below.

protocol ClassTeamMemberRatingTableViewCell {
    func sharePressed(cell: TeamMemberRatingTableViewCell)
    func ratingDidChange(for cell: TeamMemberRatingTableViewCell)
}

From this protocol, you can then access all properties in the cell (as long as they are not private) such as the title label i.e. "Planning" you can also get the indexPath in the ViewController. From there you can call a firebase function to save this data.

David Henry
  • 1,972
  • 20
  • 43