iosswiftxcodeuibarbuttonitemuiappearance

UIBarButtonItem setBackButtonTitlePositionAdjustment doesn't work


Updated

I want to change offset between Arrow and Text in Back Button in Navigation Bar. It works just fine until I set

UINavigationBar.appearance().standardAppearance = newAppearance

Here is the full code:

        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)

Solution

  • UINavigationBar.appearance() when specified overrides everything and has own settings for everything, so you need to configure offset via its own properties, like

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

    so the part of UIBarButtonItem.appearance() not needed - just remove it