ios - 如何将 UIBarButtonItem 放在 Swift4 上的 NavigationController 的 ViewController 上?

标签 ios swift xcode storyboard uibarbuttonitem

我有一个用于导航的三个屏幕。但是在其中一个中,我不能放置 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 中:(注意:“项目”按钮不会固定在栏上)

enter image description here

enter image description here

最佳答案

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

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/

相关文章:

ios - 如何以编程方式点击 iOS 键盘上的一个点

ios - 无法在 iOS 中更改 UIWebView 的背景

ios - 水平视差效果 - View 之间的相对运动

ios - 在 Ipad 上运行应用程序时未加载库

ios - 在 Swift 中使用 UIActivityIndi​​cator-for-SDWebImage

iOS:存储在 session 中过期的 cookie

ios - 核心数据文件的位置 iOS 10

ios - Xcode 错误 : unable to dequeue a cell with identifier MealTableViewCell

ios - 使用 AVAudioPlayer 开始/停止背景音乐按钮

ios - 社交媒体和我自己在应用程序中登录/注册