Back Button Image - what is it called in Swift?

2019-01-19 06:22发布

I am trying to use Swift's internal back button image. I have asked this question before and got the technically correct answer that it inherits it from the previous View, BUT if I insert this code you can control the back button on the current View.

// Takeover Back Button
self.navigationItem.hidesBackButton = false
let newBackButton = UIBarButtonItem(title: "<", style: .Plain, target: self, action: "segueBack")
navigationItem.leftBarButtonItem = newBackButton

That gives me a <, "ABC" would give me ABC etc but how do I trigger Swift to put up it's internal Back Button image. The code below doesn't work but I would have thought is along the right lines.

let backImg: UIImage = UIImage(named: "BACK_BUTTON_DEFAULT_ICON")!
navigationItem.leftBarButtonItem!.setBackgroundImage(backImg, forState: .Normal, barMetrics: .Default)

Has anyone worked out how to do this?

3条回答
走好不送
2楼-- · 2019-01-19 07:04

Try to add custom view as back button like as

var backButton = UIButton(frame: CGRectMake(0, 0, 70.0, 70.0))
var backImage = UIImage(named: "backBtn")
backButton.setImage(backImage, forState: UIControlState.Normal)
backButton.titleEdgeInsets = UIEdgeInsetsMake(10.0, 10.0, 10.0, 0.0)
backButton.setTitle("Back", forState: UIControlState.Normal)
backButton.addTarget(self, action: "buttonPressed", forControlEvents: UIControlEvents.TouchUpInside)
var backBarButton = UIBarButtonItem(customView: backButton)

var spacer = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
spacer.width = -15

self.navigationItem.leftBarButtonItems = [spacer,backBarButton]

enter image description here

It will look same as iOS back button

查看更多
迷人小祖宗
3楼-- · 2019-01-19 07:09

If you want to get the default back button image, the arrow is a class of type _UINavigationBarBackIndicatorView.

Here follows the hack,

        UIImage *imgViewBack ;

        for (UIView *view in self.navigationController.navigationBar.subviews) {
            // The arrow is a class of type _UINavigationBarBackIndicatorView. This is not any of the private methods, so I think
            // this is fine for the AppStore...
            if ([NSStringFromClass([view class]) isEqualToString:@"_UINavigationBarBackIndicatorView"]) {
                // Set the image from the Default BackBtn Imageview
                UIImageView *imgView = (UIImageView *) view;
                if(imgView){
                    imgViewBack = imgView.image ;
                }
            }
        }
查看更多
在下西门庆
4楼-- · 2019-01-19 07:13

I struggled with this question for a while. Finally I got the back image with the following code:

let backImage = navigationController?.navigationBar.subviews[2].subviews[0].subviews[0].subviews[0] as! UIImageView).image

Before run the code above, make sure the back button is showing. Then you can save backImage to anywhere you want.

Here is the backImage I got.

查看更多
登录 后发表回答