我有一个用于导航的三个屏幕。但是在其中一个中,我不能放置 UIBarButtoItem。此屏幕用于创建寄存器,我想创建一个“保存”按钮,就这么简单。当我这样做时,我选择了 Bar Button Item,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.
}
在 Storyboard 中:(注意:“项目”按钮不会固定在栏上)
最佳答案
您有多种选择,其中之一是:
You have to create a super view controller and add navigation button code in it. I have added a back button for a demo:
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)
}
}
Now you need to use the back button in your view controller which super view controller is MainViewController:
class ViewController: MainViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.addLeftBarMenuButtonEnabled = true
}
}
您可以像这样添加导航按钮并在您想要的地方使用。如果你想在每个 View Controller 中使用它,那么你必须像这样在主视图 Controller 中添加“self.addLeftBarMenuButtonEnabled = true”
class MainViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.addLeftBarMenuButtonEnabled = true
}
}
关于ios - 如何将 UIBarButtonItem 放在 Swift4 上的 NavigationController 的 ViewController 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50107011/