Setting a Custom Image for a Back Button on UINavigationBar

前端 未结 8 2172
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 10:55

I am trying to set a custom image for the back button that automatically gets place onto a navigation bar when a new view is pushed onto the stack.

I have tried add

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-14 11:11

    Since iOS 7.0 there is a new method in API backIndicatorImage. You can use it instead of setBackButtonBackgroundImage if you don't want the image to be stretched to fit the text (for example if you want a fixed size custom back arrow). Here's an example in swift:

    let image = UIImage(named: "back_button")
        
    UINavigationBar.appearance().backIndicatorImage = image
    UINavigationBar.appearance().backIndicatorTransitionMaskImage = image
    

    You can hide the text from the button using this trick:

    UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -66), for: .default)
    

    for Swift 5

    var backButtonImage = UIImage(named: "back_button")

    backButtonImage = backButtonImage?.stretchableImage(withLeftCapWidth: 15, topCapHeight: 30) UIBarButtonItem.appearance().setBackButtonBackgroundImage(backButtonImage, for: .normal, barMetrics: .default)

提交回复
热议问题