【问题标题】:How put UIBarButtonItem on ViewController of NavigationController on Swift4?如何将 UIBarButtonItem 放在 Swift4 上 NavigationController 的 ViewController 上?
【发布时间】:2018-10-10 22:22:44
【问题描述】:

我有一个用于导航的三个屏幕。但是在其中一个中,我不能放一个 UIBarButtoItem。此屏幕用于创建寄存器,我想创建一个“保存”按钮,就这么简单。当我这样做时,我选择了条形按钮项,XCode 不会让我掉在条形上。并且以编程方式也行不通。

我试过这个:(没有发生)

var btSalvar : UIBarButtonItem?

override func viewDidLoad() {
    super.viewDidLoad()
    btSalvar = UIBarButtonItem(title: "Salver", style: .plain, target: self, action: nil)
    self.navigationItem.rightBarButtonItem = btSalvar
    // Do any additional setup after loading the view.
}

在情节提要中:(注意:按钮“项目”不固定在栏上)

【问题讨论】:

  • 哪个是注册画面?
  • 我确实用屏幕编辑了问题。
  • 试试this
  • @Mannopson 谢谢,这行得通。

标签: ios swift xcode storyboard uibarbuttonitem


【解决方案1】:

您有很多选择,其中之一是:

您必须创建一个超级视图控制器并在其中添加导航按钮代码。我为演示添加了一个后退按钮:

class MainViewController: UIViewController {


    override func viewDidLoad() {
        super.viewDidLoad()
    }
    /**
     To add the left back button on navigation.
     */
    var addLeftBarMenuButtonEnabled: Bool? {
        didSet {
            if addLeftBarMenuButtonEnabled! {
                let leftBarBtn = UIButton()
                leftBarBtn.setImage(UIImage(named: "backIcon"), for: .normal)
                leftBarBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
                leftBarBtn.addTarget(self, action: #selector(actionBackButton), for: .touchUpInside)
                self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: leftBarBtn)
            } else {
                self.navigationItem.setHidesBackButton(true, animated: true)
            }
        }
    }
    ///This is action method for back button
    @objc func actionBackButton() {
        self.view.endEditing(true)
        self.navigationController?.popViewController(animated: true)
    }
}

现在你需要在你的视图控制器中使用返回按钮,超级视图控制器是 MainViewController:

class ViewController: MainViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.addLeftBarMenuButtonEnabled = true
    }

}

您可以添加这样的导航按钮并在您想要的地方使用。如果你想在每个视图控制器中使用它,那么你必须在主视图控制器中添加'self.addLeftBarMenuButtonEnabled = true'

 class MainViewController: UIViewController {


        override func viewDidLoad() {
            super.viewDidLoad()
            self.addLeftBarMenuButtonEnabled = true
        }
    }

【讨论】:

  • 没有更简单的解决方案?
  • 这是一个非常简单的解决方案...看起来很难,但它可以在您的项目中重复使用。如果需要,则从 MainViwcontroller 复制按钮代码并将此代码添加到视图控制器中,您可以在其中添加导航按钮
  • 我确实用过这个:stackoverflow.com/questions/45069477/…。完美运行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多