Skip to content

Instantly share code, notes, and snippets.

@simonbs
Created July 23, 2021 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonbs/ab6c5e0985e760f6fc6f80eec490755a to your computer and use it in GitHub Desktop.
Save simonbs/ab6c5e0985e760f6fc6f80eec490755a to your computer and use it in GitHub Desktop.
Enable/disable a toolbar item in a Catalyst app.
final class ToolbarController, NSObject, NSToolbarDelegate {
var isBackButtonEnabled = false {
didSet {
if isBackButtonEnabled != oldValue {
reloadBackItem()
}
}
}
func toolbar(_ toolbar: NSToolbar, itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, willBeInsertedIntoToolbar flag: Bool) -> NSToolbarItem? {
switch itemIdentifier {
case .back:
return makeBackToolbarItem()
default:
return nil
}
}
}
private extension ToolbarController {
private func makeBackToolbarItem() -> NSToolbarItem {
let imageConfiguration = UIImage.SymbolConfiguration(scale: .large)
let image = UIImage(systemName: "chevron.backward", withConfiguration: imageConfiguration)
let barButtonItem = UIBarButtonItem(image: image, style: .plain, target: nil, action: nil)
let item = NSToolbarItem(itemIdentifier: .back, barButtonItem: barButtonItem)
item.isNavigational = true
item.toolTip = L10n.Toolbar.Tooltip.back
if isBackButtonEnabled {
item.target = self
item.action = #selector(back)
} else {
item.target = nil
item.action = nil
}
return item
}
private func reloadBackItem() {
// Remove and re-insert the back item to update it's enabled/disabled state.
// Just setting the target/action won't immediately reload the item.
// It will only happen when the user performs an action like scrolling.
if let idx = toolbar.items.firstIndex(where: { $0.itemIdentifier == .back }) {
toolbar.removeItem(at: idx)
toolbar.insertItem(withItemIdentifier: .back, at: 0)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment