UIBarButtonItem setBackButtonTitlePositionAdjustment 不起作用

UIBarButtonItem setBackButtonTitlePositionAdjustment doesn't work

已更新

我想更改导航栏后退按钮中箭头和文本之间的偏移量。它工作得很好,直到我设置

UINavigationBar.appearance().standardAppearance = newAppearance

完整代码如下:

        let appearance = UINavigationBar.appearance()
        let standardAppearance = UINavigationBarAppearance()
        standardAppearance.configureWithOpaqueBackground()
        standardAppearance.backgroundColor = someColor
        standardAppearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor: titleColor]
        standardAppearance.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor: titleColor]
        standardAppearance.shadowColor = navigationShadowColor

        // if remove theses 2 line, offset code works!!!
        appearance.standardAppearance = standardAppearance
        appearance.scrollEdgeAppearance = standardAppearance

        // code to set offset
        UIBarButtonItem
            .appearance()
            .setBackButtonTitlePositionAdjustment(
                UIOffset(horizontal: -20, vertical: 0),
                for: .default)

这是我的自定义后退按钮代码

func addBackButton() {
    let backButtonView = UIView(frame: CGRect(x: 0, y: 0, width: 70, height: 44))
    let imageView = UIImageView(image: UIImage(named: "back-arrow"))
    imageView.frame = CGRect(x: -5, y: 11, width: 12, height: 22)
    imageView.image = imageView.image!.withRenderingMode(.alwaysTemplate)
    imageView.tintColor = .fiGreen()
    let label = UILabel(frame: CGRect(x: 10, y: 0, width: 60, height: 44))
    label.textColor = .fiGreen()
    label.text = NSLocalizedString("back", comment: "Back")
    backButtonView.addSubview(imageView)
    backButtonView.addSubview(label)
    backButtonView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(backButtonClicked)))
    let barButton = UIBarButtonItem(customView: backButtonView)
    navigationItem.leftBarButtonItem = barButton
}    

我想你可以修改它以获得你需要的偏移量。

您需要在应用程序委托方法中设置 TitlePositionAdjustment "didFinishLaunchingWithOptions" 才能正常工作。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    UIBarButtonItem
    .appearance()
    .setBackButtonTitlePositionAdjustment(
        UIOffset(horizontal: -20, vertical: 0),
        for: .default)
    return true
}

UINavigationBar.appearance() 指定时会覆盖所有内容并且对所有内容都有自己的设置,因此您需要通过其自己的属性配置偏移量,例如

...
standardAppearance.backButtonAppearance.normal.titlePositionAdjustment = 
    UIOffset(horizontal: -20, vertical: 0)

appearance.standardAppearance = standardAppearance
...

所以 UIBarButtonItem.appearance() 的部分不需要 - 只需删除它