Short answer

Nine iOS notes from July 2019, checked again: disabling a bar button (the 2019 comments had enabled and disabled swapped); popping back to a screen that's already in the stack, not to a new instance; highlight colors in collection view cells; button shadows with a shadow path; what error 2003334207 means (an unspecified audio file error, which an empty file reproduced here); playing short sounds without reloading the file; a view above the keyboard with keyboardLayoutGuide; and a custom segmented control built from a collection view, tested.

SWIFT TIPS · UIKIT · 9 NOTES

First posted on July 9, 2019, as "9 Notes for me in July Swift 4.2". Rewritten on November 19, 2026. The tests were run as Mac Catalyst programs with Swift 6.2.3 (Xcode 26.2, Swift 5 mode) on macOS 26.0.1, and every code block was type-checked for an iOS 15 target. The sound test loaded a generated tone but didn't play it. Nothing was run on an iPhone or a simulator.

Several July 2019 notes come from small practice screens in a project I called 100DayOfCode: a piano made of collection view cells, a custom tab bar, a sound that wouldn't play. The others are navigation and button fixes.

The two longest notes were full view controllers pasted without explanation. In this rewrite they're shorter, they compile, and the custom segmented control was run as a real collection view on this Mac, so the selection behavior below is a test result, not a guess.

1. Disable a bar button item

2019: navigationItem.rightBarButtonItem?.isEnabled, with true commented "for disable" and false "for enable".

Now: the comments were the wrong way round. isEnabled = false disables:

isEnabled = false -> disabled
isEnabled = true  -> enabled

A disabled item is drawn dimmed and its action isn't sent. The optional chaining matters too: if the item doesn't exist yet, the line does nothing, so set isEnabled after you create the button, for example in viewDidLoad, and update it whenever the condition changes, such as when a form becomes valid.

2. Pop back to a specific screen

2019: popToViewController(PayAndPurchaseViewController(), animated: true), and if that fails, loop over viewControllers and pop to the one that is PayAndPurchaseViewController.

Now: the first line can't work. PayAndPurchaseViewController() makes a brand-new instance, which isn't in the stack; the screen you want is a different object of the same class. I ran both on this Mac:

stack: ["HomeViewController", "PayAndPurchaseViewController", "ReceiptViewController"]
a new PayAndPurchaseViewController() is in the stack: false
after popping to the existing instance: ["HomeViewController", "PayAndPurchaseViewController"]

And the first version, with a new instance:

Calling popToViewController(PayAndPurchaseViewController(), animated: false) ...
returned, stack size: 3

On Mac Catalyst it returned and left all three screens in place, so the button simply did nothing. I didn't test what an iPhone does with it. Either way the fix is the loop the note gave as plan B; the 2019 closure was also missing its in keyword, so it didn't compile. As an extension:

import UIKit

final class PayAndPurchaseViewController: UIViewController {}

extension UINavigationController {
    /// Pops back to the first view controller of the given type that is already in the stack.
    /// Returns false (and does nothing) if there is none.
    @discardableResult
    func popToFirst<T: UIViewController>(_ type: T.Type, animated: Bool = true) -> Bool {
        guard let target = viewControllers.first(where: { $0 is T }) else { return false }
        popToViewController(target, animated: animated)
        return true
    }
}

final class ReceiptViewController: UIViewController {
    @objc func backToPayment() {
        if navigationController?.popToFirst(PayAndPurchaseViewController.self) != true {
            navigationController?.popToRootViewController(animated: true)
        }
    }
}

Returning a Boolean lets the caller fall back, here to the root, when the screen isn't in the stack because the person arrived another way.

3. Highlight a collection view cell while it's touched

2019: implement didHighlightItemAt and didUnhighlightItemAt, get the cell with cellForItem(at:), and change its background color. "You must include UICollectionViewDelegateFlowLayout."

Now: those two methods belong to UICollectionViewDelegate; the flow layout protocol inherits from it, which is why it worked. The approach has a gap: the color lives on whatever cell object was on screen, so after scrolling, a reused cell can show a stale highlight. Letting the cell style itself from isHighlighted and isSelected avoids that:

import UIKit

final class TileCell: UICollectionViewCell {
    override var isHighlighted: Bool { didSet { updateBackground() } }
    override var isSelected: Bool { didSet { updateBackground() } }

    private func updateBackground() {
        contentView.backgroundColor = isHighlighted || isSelected ? .systemGray4 : .systemBackground
    }
}

// iOS 14 and later can also describe the states in a configuration:
@available(iOS 14.0, *)
final class ConfiguredTileCell: UICollectionViewCell {
    override func updateConfiguration(using state: UICellConfigurationState) {
        var background = UIBackgroundConfiguration.listPlainCell().updated(for: state)
        background.backgroundColor = state.isHighlighted || state.isSelected ? .systemGray4 : .systemBackground
        backgroundConfiguration = background
    }
}
touch down  -> systemGray4
touch up    -> systemBackground
selected    -> systemGray4

UIKit sets isHighlighted during the touch and isSelected after a tap, on whichever cell is showing that item, so the view controller needs no delegate code at all. On iOS 14 and later, updateConfiguration(using:) with a background configuration does the same in one place.

4. A shadow on a button

2019: set shadowColor, shadowOffset, shadowOpacity 1.0, shadowRadius 0, masksToBounds = false and cornerRadius 4.

Now: still the right properties. A radius of 0 gives a hard-edged shadow, which is a style choice; most designs use a few points of blur and a lower opacity. masksToBounds must stay false, or the layer clips the shadow away. What I'd add is a shadowPath: without one, Core Animation works out the shadow's shape from the layer's contents, which costs time in a scrolling list.

import UIKit

final class ShadowButton: UIButton {
    override init(frame: CGRect) {
        super.init(frame: frame)
        layer.cornerRadius = 8
        layer.cornerCurve = .continuous
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOpacity = 0.25
        layer.shadowOffset = CGSize(width: 0, height: 2)
        layer.shadowRadius = 4          // 0 gives a hard edge, as in the 2019 code
        layer.masksToBounds = false     // a clipped layer can't draw a shadow outside itself
    }

    required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }

    override func layoutSubviews() {
        super.layoutSubviews()
        // An explicit path saves Core Animation from working the shape out every frame.
        layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).cgPath
    }
}
masksToBounds: false | shadowPath bounds: (0.0, 0.0, 160.0, 44.0)

Set the path in layoutSubviews so it follows the button's size. The October 2019 notes cover glow shadows, where the offset is zero.

5. Error Domain=NSOSStatusErrorDomain Code=2003334207

2019: don't rename audio files from one format to another, such as do.wav to do.mp3; the file isn't recognized or is corrupted. Try playing it in Xcode to check.

Now: the number is a four-character code. 2003334207 is 0x7768743F, the letters wht?, which AudioFile.h names kAudioFileUnspecifiedError. I tried several broken files with AVAudioPlayer:

2003334207 as four characters: 'wht?'
AVAudioPlayer with a text file named .wav: NSOSStatusErrorDomain 1954115647 'typ?'

Only the empty file gave 2003334207. A renamed or damaged file gave typ? (unsupported file type) or dta? (invalid file). So for this exact code, check that the file in the app bundle actually has content: a file that failed to copy or download, or a placeholder of zero bytes, are good suspects. The 2019 advice still holds for the other two codes, and the four-character trick works for most large OSStatus numbers: write it in hexadecimal and read the bytes as letters.

6. Playing a piano note

2019: a view controller with seven collection view cells; tapping a cell loads do-octave.wav into a new AVAudioPlayer and plays it.

Now: it plays, but it reopens the file on every tap, so fast taps lag, and the audio session was activated without a category. A small player class loads each note once:

import AVFoundation
import UIKit

final class NotePlayer {
    private var players: [String: AVAudioPlayer] = [:]

    /// Loads each file once, so a tap plays at once instead of reading the file again.
    func preload(_ names: [String], ext: String = "wav") {
        try? AVAudioSession.sharedInstance().setCategory(.ambient)   // respects the silent switch
        for name in names {
            guard let url = Bundle.main.url(forResource: name, withExtension: ext) else {
                print("Missing \(name).\(ext): check Target Membership and Copy Bundle Resources")
                continue
            }
            do {
                let player = try AVAudioPlayer(contentsOf: url)
                player.prepareToPlay()
                players[name] = player
            } catch {
                print("Can't open \(name).\(ext):", error)
            }
        }
    }

    func play(_ name: String) {
        guard let player = players[name] else { return }
        player.currentTime = 0
        player.play()
    }
}

final class PianoViewController: UIViewController {
    let notes = ["do", "re", "mi", "fa", "sol", "la", "si"]
    let player = NotePlayer()

    override func viewDidLoad() {
        super.viewDidLoad()
        player.preload(notes)
    }

    func didTapKey(at index: Int) {
        player.play(notes[index])
    }
}

I checked the loading part with a half-second tone generated in code, without playing it:

tone file loaded: duration 0.50 s | prepareToPlay: true | played: no (kept silent)

The .ambient category mixes with other audio and goes quiet when the ring/silent switch is on, which suits sound effects. Use .playback for an instrument app that should sound even in silent mode. The missing-file message points at the usual cause of a sound that never plays: the file isn't in Copy Bundle Resources.

7. A view above the keyboard

2019: add a view to UIApplication.shared.windows.last with a huge zPosition, from Stack Overflow, so it sits over the keyboard.

Now: this depends on the keyboard's private window being last in the list, which UIKit doesn't promise, and windows is deprecated since iOS 15:

Overlay.swift:2:54: warning: 'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead

If the goal is a bar that stays on top of the keyboard, such as a message composer, iOS 15 added keyboardLayoutGuide. Pin the view to it and the view moves with the keyboard, and rests on the bottom safe area when the keyboard is hidden:

import UIKit

final class ChatViewController: UIViewController {
    let composer = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()
        composer.backgroundColor = .secondarySystemBackground
        composer.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(composer)
        NSLayoutConstraint.activate([
            composer.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            composer.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            composer.heightAnchor.constraint(equalToConstant: 56),
            // iOS 15: the guide follows the keyboard, and the bottom safe area when it's hidden.
            composer.bottomAnchor.constraint(equalTo: view.keyboardLayoutGuide.topAnchor)
        ])
    }
}

For a bar that belongs to one text field, inputAccessoryView is the other standard option. If you really need to cover the keyboard, for example with a custom number pad, use inputView on the text field instead.

8. A custom segmented control

2019: just a screen recording of the result, a row of image tabs, with the code in note 9:

It's a good example of when a UISegmentedControl isn't enough: images that change when selected, seven equal tabs, and full control over colors. A horizontal collection view gives you that, as the next note shows.

9. The segmented control's code

2019: a view controller with a parallel array of Booleans for which tab is active, an int21 variable for the selected index, color changes in didHighlightItemAt and didUnhighlightItemAt, reloadData() after every touch, and a cell that sets the same image for five tabs.

Now: the collection view already tracks selection, so the parallel arrays and the reload can go. The cell draws itself from isSelected, as in note 3, and the view controller reports the chosen index through a closure:

import UIKit

final class DayTabCell: UICollectionViewCell {
    let label = UILabel()

    override init(frame: CGRect) {
        super.init(frame: frame)
        label.textAlignment = .center
        label.frame = contentView.bounds
        label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        contentView.addSubview(label)
        updateColors()
    }

    required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }

    override var isSelected: Bool { didSet { updateColors() } }
    override var isHighlighted: Bool { didSet { updateColors() } }

    private func updateColors() {
        contentView.backgroundColor = isSelected ? .systemBlue : (isHighlighted ? .systemGray4 : .systemGray6)
        label.textColor = isSelected ? .white : .label
    }
}

final class DayTabsViewController: UIViewController, UICollectionViewDataSource,
                                   UICollectionViewDelegateFlowLayout {
    let days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
    var onSelect: ((Int) -> Void)?
    private lazy var collectionView = UICollectionView(frame: .zero,
                                                       collectionViewLayout: UICollectionViewFlowLayout())

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.frame = view.bounds
        collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        collectionView.register(DayTabCell.self, forCellWithReuseIdentifier: "day")
        collectionView.dataSource = self
        collectionView.delegate = self
        view.addSubview(collectionView)
        collectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: false, scrollPosition: [])
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        days.count
    }

    func collectionView(_ collectionView: UICollectionView,
                        cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "day", for: indexPath) as! DayTabCell
        cell.label.text = days[indexPath.item]
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        onSelect?(indexPath.item)       // the selected cell updates itself through isSelected
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {
        let flow = collectionViewLayout as? UICollectionViewFlowLayout
        let spacing = (flow?.minimumInteritemSpacing ?? 0) * CGFloat(days.count - 1)
        let width = ((collectionView.bounds.width - spacing) / CGFloat(days.count)).rounded(.down)
        return CGSize(width: width, height: collectionView.bounds.height)
    }
}

I ran this code as is, with a 350 point wide view, selected Thursday the way a tap does, and read back which cell was blue:

visible cells: 7 | first cell size: (41.0, 44.0)
start:         [Mon] Tue Wed Thu Fri Sat Sun
select Thu:    Mon Tue Wed [Thu] Fri Sat Sun | onSelect got: 3

All seven cells fit at 41 by 44 points, Monday started selected, and selecting Thursday moved the highlight with no reload; the brackets mark the blue cell. For images, add a UIImageView to the cell and switch its image in updateColors.

What the 2019 version said

The post had no screenshots, only the screen recording, which is kept in note 8.

Sources