为什么当我以编程方式添加按钮和标题时,它们没有显示在导航栏上?

Why is button and title not showing up on navigation bar when I add them programmatically?

我试图以编程方式制作带有按钮和标题的导航栏。出于某种原因,导航栏出现了,但按钮和标题没有出现。你如何解决这个问题?

    // Create the navigation bar
    let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, 500, 200))

    //Create navigation bar's title
    self.navigationController?.navigationBar.topItem?.title = "Edit"

    //Create back button
    let backBtn = UIButton(type: UIButtonType.Custom)
    let backButtonItem = UIBarButtonItem(customView: backBtn)
    self.navigationItem.leftBarButtonItem = backButtonItem

    //Add navigation bar to view
    self.view.addSubview(navigationBar)

对于你的问题,因为你没有嵌入 viewcontroller 到导航控制器,所以你所有的设置都没有意义

self.navigationController? = nil & 
self.navigationItem.leftBarButtonItem //there's no navigationcontroller made no sense

你需要做的是,像

一样在适当的时候嵌入vc到navigationcontroller
let navVC = UINavigationController(rootViewController: vc)

然后你可以导航控制器并设置所有东西