diff --git a/iOSTemplate/RatingControl.swift b/iOSTemplate/RatingControl.swift index 8e34e43b428a1faa439caf0551e043b581d9f682..2771b3d45c2b00933932afca6d40e57c32749070 100644 --- a/iOSTemplate/RatingControl.swift +++ b/iOSTemplate/RatingControl.swift @@ -22,7 +22,12 @@ import UIKit setupButtons() } } - var rating = 0 + + var rating = 0 { + didSet { + updateButtonSelectionStates() + } + } // MARK: Initialization override init(frame: CGRect) { @@ -37,7 +42,20 @@ import UIKit // MARK: Button Action @objc func ratingButtonTapped(button: UIButton) { - print("Button pressed 👍") + guard let index = ratingButtons.index(of: button) else { + fatalError("The button, \(button), is not in the ratingButtons array: \(ratingButtons)") + } + + // Calculate the rating of the selected button + let selectedRating = index + 1 + + if selectedRating == rating { + // If the selected star represents the current rating, reset the rating to 0. + rating = 0 + } else { + // Otherwise set the rating to the selected star + rating = selectedRating + } } // MARK: Private Methods @@ -79,6 +97,14 @@ import UIKit // Add the new button to the rating button array ratingButtons.append(button) } + + updateButtonSelectionStates() } + private func updateButtonSelectionStates() { + for (index, button) in ratingButtons.enumerated() { + // If the index of a button is less than the rating, that button should be selected. + button.isSelected = index < rating + } + } }