// // RatingControl.swift // iOSTemplate // // Created by John Hampton on 3/3/19. // import UIKit @IBDesignable class RatingControl: UIStackView { // MARK: Properties private var ratingButtons = [UIButton]() @IBInspectable var starSize: CGSize = CGSize(width: 44.0, height: 44.0) { didSet { setupButtons() } } @IBInspectable var starCount: Int = 5 { didSet { setupButtons() } } var rating = 0 { didSet { updateButtonSelectionStates() } } // MARK: Initialization override init(frame: CGRect) { super.init(frame: frame) setupButtons() } required init(coder: NSCoder) { super.init(coder: coder) setupButtons() } // MARK: Button Action @objc func ratingButtonTapped(button: UIButton) { 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 private func setupButtons() { // Clear any existing buttons for button in ratingButtons { removeArrangedSubview(button) button.removeFromSuperview() } ratingButtons.removeAll() // Load Button Images let bundle = Bundle(for: type(of: self)) let filledStar = UIImage(named: "filledStar", in: bundle, compatibleWith: self.traitCollection) let emptyStar = UIImage(named:"emptyStar", in: bundle, compatibleWith: self.traitCollection) let highlightedStar = UIImage(named:"highlightedStar", in: bundle, compatibleWith: self.traitCollection) for _ in 0..