Modal UINavigationController shown programmatically has no navigation buttons

When I create a modal segue to a navigation controller in a storyboard, the navigation bar buttons appear correctly. But when trying to recreate this programmatically, no buttons appear:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let button = UIButton(type: .infoLight, primaryAction: UIAction(handler: { _ in
            self.present(UINavigationController(rootViewController: ModalViewController()), animated: true)
        }))
        button.frame.origin = CGPoint(x: 100, y: 100)
        view.addSubview(button)
    }


}

class ModalViewController: UIViewController {
    
    override func loadView() {
        let button = UIBarButtonItem(title: "button")
        button.primaryAction = UIAction(handler: { action in
        })
        button.style = .done
        navigationItem.title = "title"
        navigationItem.rightBarButtonItem = button
        view = UITableView()
    }
    
}

What am I doing wrong?

Answered by Frameworks Engineer in 809291022

When you set the primary action, we take the title & image from that action for the bar button item, and since you created an action with no title or image, we end up discarding the title you previously set and you have a title-less button.

Accepted Answer

When you set the primary action, we take the title & image from that action for the bar button item, and since you created an action with no title or image, we end up discarding the title you previously set and you have a title-less button.

When you set the primary action, we take the title & image from that action for the bar button item

Thanks! I see now that the documentation for primaryAction says this as well. Though in other places in my project I use

let button = UIBarButtonItem(title: "button", primaryAction: UIAction(handler: { action in
    ...
}))

which works fine and I assumed was the same as

let button = UIBarButtonItem(title: "button")
button.primaryAction = UIAction(handler: { action in
    ...
})
Modal UINavigationController shown programmatically has no navigation buttons
 
 
Q