Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

ios - swift: setting back button image in nav bar

I'm trying to set the back button image in nav bar in my controller, here's my code in viewDidLoad():

        var backImg: UIImage? = UIImage(named: "back_btn.png")
    println(backImg)
    if var back_img = backImg  {
        println("GET IT")
        println(back_img)
        println(UIControlState.Normal)
        println(UIBarMetrics.Default)
    self.navigationController.navigationBar.backItem.backBarButtonItem.setBackButtonBackgroundImage(back_img, forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)
    }

I tried to put them to viewWillLoad, but getting the same error

Console with error message:

<UIImage: 0x7ff37bd85750>
GET IT
<UIImage: 0x7ff37bd85750>
VSC14UIControlState (has 1 child)
(Enum Value)
fatal error: unexpectedly found nil while unwrapping an Optional value

I don't know which part went wrong. Seems like the back_img is not nil, but I got error saying it's nil

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Swift 3.0 + put below code in appdelegate didFinishLaunchingWithOptions method, it will work perfectly

let backImage = UIImage(named: "BackNavigation")?.withRenderingMode(.alwaysOriginal)
UINavigationBar.appearance().backIndicatorImage = backImage
UINavigationBar.appearance().backIndicatorTransitionMaskImage = backImage
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -80.0), for: .default)

Or for Swift 4.0 +

let backImage = UIImage(named: "back-icon").withRenderingMode(.alwaysOriginal)
UINavigationBar.appearance().backIndicatorImage = backImage
UINavigationBar.appearance().backIndicatorTransitionMaskImage = backImage
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: -80.0), for: .default)

The last line will remove the title of Navigation Back Button if you don't want to remove title then just remove last line


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...