如何在Swift 5上向后移动NavigationController中的自定义按钮

问题描述 投票:0回答:2

我在使用UI时遇到问题。我正在使用navigationController移动屏幕。

但是我不想使用基本的后退按钮,所以我隐藏了基本的后退按钮,将导航栏添加到情节提要中,

并添加了一些项目以使后退按钮。但是,该屏幕不会移至上一个屏幕。如何进入上一个屏幕?

Basic backButton //我现在将其隐藏。

back

我想使用我制作的后退按钮。

enter image description here

用于后退按钮项目的后退命令。

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        self.navigationController?.setNavigationBarHidden(true, animated: animated)
    }

    @IBAction func backButton(_ sender: UIBarButtonItem) {
        self.dismiss(animated: false, completion: nil) // Did not worked!
    }

此外,我想删除导航标题的下划线。如何删除它?

ios swift navigation uinavigationcontroller
2个回答
0
投票

您可以使用以下代码自定义后退按钮

    let buttonView = UIView(frame: CGRect(x: 0, y: 0, width: 25, height: 25))


let buttonImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 25, height: 25))
        buttonImageView.contentMode = .scaleAspectFit
        buttonImageView.image = UIImage(named: "back_button")

        let btnLogo = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        btnLogo.setTitle("", for: .normal)
        btnLogo.backgroundColor = UIColor.clear
        btnLogo.layer.masksToBounds = true
        btnLogo.addTarget(self, action: #selector(backButton), for: .touchUpInside)
        buttonView.addSubview(buttonImageView)
        buttonView.addSubview(btnLogo)

        let barButton = UIBarButtonItem(customView: buttonView)
        self.navigationItem.leftBarButtonItem = barButton

如果使用导航栏,则应使用navigationController.popViewController而不是dismiss方法


0
投票

我在相同情况下在项目中使用它:

UIApplication.shared.keyWindow?.rootViewController?.dismiss(animated: false, completion: nil)

可在iOS 13弃用keyWindow后使用:

let keyW = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
keyW?.rootViewController?.dismiss(animated: false, completion: nil)

也可以使用:

self.navigationController?.popViewController(animated: false)

self.navigationController?.popToRootViewController(animated: false)
© www.soinside.com 2019 - 2024. All rights reserved.