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

时间:2016-01-02 04:27:38

标签: 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)

1 个答案:

答案 0 :(得分:1)

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

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

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

let navVC = UINavigationController(rootViewController: vc)

然后你可以使用navigationController并设置所有东西