首页 > 解决方案 > 导航栏中的后退按钮重叠,快速 4

问题描述

我试图根据教程自定义我的后退按钮。在 AppDelegate 中,

let barButtonAppearence = UIBarButtonItem.appearance()

func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
    let backButton = UIImage(named: "back_arrow")
    let backButtonImage = backButton?.stretchableImage(withLeftCapWidth: 0, topCapHeight: 10)
    barButtonAppearence.setBackButtonBackgroundImage(backButtonImage, for: .normal, barMetrics: .default)
    return true
}

然后它与现有的冲突(由于segue(Show)而自动出现。

在此处输入图像描述

所以我需要删除蓝色的。

标签: swiftuinavigationbar

解决方案


有两件事需要完成你想要达到的目标:

  • 将后退按钮的默认图像更改为您提供的图像
  • 从后退按钮项目中删除标题

要更改返回按钮的图像:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Remember, this will change every navigation bar's back button image in your app
    UINavigationBar.appearance().backIndicatorImage = #imageLiteral(resourceName: "backButton")
    UINavigationBar.appearance().backIndicatorTransitionMaskImage = #imageLiteral(resourceName: "backButton")
    return true
}

注意:如果您不希望所有导航栏后退按钮都具有提供的图像,则可能需要子类化UINavigationController并更新其导航栏。

从后退按钮项中删除标题:

我们将通过向 any UIViewControllerthrough 扩展添加一个方法来做到这一点。此处将使用扩展方法,以便任何人UIViewController都可以在需要时具有此行为。

extension UIViewController {
    func removeNavigationBarBackButtonItemTitle() {
        self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItem.Style.plain, target: nil, action: nil)
    }
}

现在,在VC A -> VC B的任何推送转换中,您需要隐藏后退按钮的标题。但是您必须removeNavigationBarBackButtonItemTitle()VC A调用该方法。只要记住这一点,你就可以开始了。

class ViewControllerA: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        removeNavigationBarBackButtonItemTitle()
    }
}

你会在这里找到一个演示。该演示也有一些其他的实现。但是你会得到你需要的和我上面所说的。


推荐阅读