Using the Custom Control

MoodSelectionViewController has grown to encompass multiple responsibilities, including managing the selection control. Now that you have created the ImageSelector class, there is a lot of code that is no longer needed within the view controller. This is a good thing; cleaning up your view controller will make its responsibility more clear.

Open MoodSelectionViewController.swift and start by replacing the stack view outlet with an image selector outlet.

Listing 18.7  Replacing the stack view with an image selector (MoodSelectionViewController.swift)

@IBOutlet var stackView: UIStackView!
@IBOutlet var moodSelector: ImageSelector!

You will still need the array of Mood instances, but the property observer can be greatly simplified. Update the property observer to set the images on the moodSelector.

Listing 18.8  Setting the mood selector images (MoodSelectionViewController.swift)

var moods: [Mood] = [] {
    didSet {
        currentMood = moods.first
        moodButtons = moods.map { mood in
            let moodButton = UIButton()
            moodButton.setImage(mood.image, for: .normal)
            moodButton.imageView?.contentMode = .scaleAspectFit
            moodButton.adjustsImageWhenHighlighted = false
            moodButton.addTarget(self,
                                 action: #selector(moodSelectionChanged(_:)),
                                 for: .touchUpInside)
            return moodButton
        }
        moodSelector.images = moods.map { $0.image }
    }
}

Also, remove the moodButtons property, as the ImageSelector is now managing the buttons.

Listing 18.9  Removing the moodButtons property (MoodSelectionViewController.swift)

var moodButtons: [UIButton] = [] {
    didSet {
        oldValue.forEach { $0.removeFromSuperview() }
        moodButtons.forEach { stackView.addArrangedSubview($0)}
    }
}

Now, update the moodSelectionChanged(_:) method. It will now be an @IBAction connected in the storyboard to the ImageSelector instance.

Listing 18.10  Updating the mood selection action (MoodSelectionViewController.swift)

@objc private func moodSelectionChanged(_ sender: UIButton) {
    guard let selectedIndex = moodButtons.firstIndex(of: sender) else {
        preconditionFailure("Unable to find the tapped button in the buttons array.")
    }
@IBAction private func moodSelectionChanged(_ sender: ImageSelector) {
    let selectedIndex = sender.selectedIndex

    currentMood = moods[selectedIndex]
}

With the code changes finished, you are ready to update the interface.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.94.153