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

标签 swift uinavigationbar uibarbuttonitem navigationbar

我尝试以编程方式使用按钮和标题制作导航栏。由于某种原因,导航栏显示,但按钮和标题没有显示。你如何解决这个问题?

    // 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)

最佳答案

对于你的问题,由于你没有将 View Controller 嵌入到导航 Controller 中,所以你的所有设置都没有意义

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

你需要做的是,在适当的时候将vc嵌入到navigationcontroller

let navVC = UINavigationController(rootViewController: vc)

然后你可以使用 navigationController 并设置所有内容

关于swift - 当我以编程方式添加按钮和标题时,为什么按钮和标题没有显示在导航栏上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34562599/

相关文章:

ios5 - 隐藏 ios 5 导航 Controller 中的默认导航栏

objective-c - UINavigationController - 推送时保持导航栏相同

swift - 将 NSAttributedString 添加到 UIBarButtonItem

ios - 如何隐藏/显示导航栏中的右键

SwiftUI ViewModel 不更新计算变量

ios - UIImageView图层边框问题

ios - Swift:DismissViewController() 和关闭键盘的线程问题

ios - 如何在 Swift 的第一个 ViewController 中隐藏导航栏?

ios - iOS版本检查UIBarButtonSystemItemPageCurl是否存在

ios - 从 UIColors 或 NSColors 数组创建 CGColors 数组