提交 2c2455b2 编写于 作者: J John Hampton

Implement the button action

上级 d3601c50
......@@ -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
}
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册