无法在viewcontroller上创建UIBarButtonItem

时间:2019-01-16 08:14:15

标签: swift xcode

我正在尝试通过执行以下功能来添加UIBarButtonItem:

func setupBackButton() {
        let button = UIButton(type: .custom)
        button.setTitle("Done", for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 40)

        let barButton = UIBarButtonItem(customView: button)
        //assign button to navigationbar
        self.navigationItem.leftBarButtonItem = barButton
    }

它可以在我添加它的其他屏幕上使用, 但是在spefic视图控制器上,它什么也没添加。

这是在其上可以工作的其他屏幕的故事板:

enter image description here

enter image description here

这是屏幕上无法使用的sotryboard:

enter image description here

enter image description here

可能是问题所在,为什么我可能看不到按钮?

2 个答案:

答案 0 :(得分:0)

迅速4:

我添加了一个导航控制器: enter image description here

在viewcontroller上创建UIBarButtonItem:

    override func viewDidLoad() {
    super.viewDidLoad()

    let leftBarButton = UIBarButtonItem(title: "Edit", style: .done, target: self, action: #selector(myLeftBarButtonItem(_:)))
    self.navigationItem.leftBarButtonItem = leftBarButton
}


@objc func myLeftBarButtonItem(_ sender:UIBarButtonItem!) {
    print("myLeftBarButtonItem")
}

enter image description here

答案 1 :(得分:0)

您可以尝试以下操作: 如果您在左侧导航栏中添加图片,请输入以下内容:

let leftAddBarButtonItemMenu = UIBarButtonItem(image: #imageLiteral(resourceName: "menu"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.btnLeftMenuClicked(sender:)))
navigationItem.leftBarButtonItems = [leftAddBarButtonItemMenu]

如果您在右侧导航栏中添加图片,请输入以下内容:

let rightNavBarItem = UIBarButtonItem(image: #imageLiteral(resourceName: "menu"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.btnRightClicked(sender:)))
navigationItem.rightBarButtonItem = [rightNavBarItem]

如果在右侧导航栏中添加标题,请输入以下内容:

let rightNavBarItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.btnRightClicked(sender:)))
navigationItem.rightBarButtonItem = [rightNavBarItem]

它可能会帮助您。谢谢