Skip to content

Commit

Permalink
Update rating on click in RatingControl class
Browse files Browse the repository at this point in the history
  • Loading branch information
DipanshKhandelwal committed Oct 20, 2019
1 parent 1d1e4fb commit fbe0ccb
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions food-tracker-app/RatingControl.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ import UIKit
//MARK: Properties
private var ratingButtons = [UIButton]()

var rating = 0
var rating = 0 {
didSet {
updateButtonSelectionStates()
}
}

@IBInspectable var starSize: CGSize = CGSize(width: 44.0, height: 44.0) {
didSet {
Expand All @@ -40,7 +44,20 @@ import UIKit

//MARK: Button Action
@objc func ratingButtonTapped(button: UIButton) {
print("Button pressed 👍")
guard let index = ratingButtons.firstIndex(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
Expand Down Expand Up @@ -83,5 +100,15 @@ 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
}
}

}

0 comments on commit fbe0ccb

Please sign in to comment.