how to replace/customize back button image in storyboard navigationcontroller

别来无恙 提交于 2019-11-28 04:11:19

问题


I want to replace the text in the back button with a custom image. How can I do that in swift code? I don't want to replace the entire backbarbutton since I'd like to keep the default action behaviour of going back to the last view. I would also like to do a switch statement based on where the back destination(based on storyboardId) is so that I can show different images based on the view.

this replaces the image but it wipes out the default back button behavior, and I need to discrimante on what the back destination is so that I can show the right back image.

self.navigationItem.leftBarButtonItem = 
 UIBarButtonItem(image:StyleKit.imageOfMap, style:.Plain, target:self, action:nil);

回答1:


Try changing your leftBarButtonItem:

self.navigationItem.leftBarButtonItem = 
    UIBarButtonItem(image:StyleKit.imageOfMap, style:.Plain, target:self, action:nil);

to a backBarButtonItem:

self.navigationItem.backBarButtonItem = 
    UIBarButtonItem(image:StyleKit.imageOfMap, style:.Plain, target:self, action:nil);

in order to take advantage of backBarButtonItem's default action.

And put that line of code in the view controller preceding the one you'd like your custom back button to appear in.

Edit: If you don't want the "<" symbol to appear on your button, you'll have to in fact use a leftBarButtonItem then dismiss the view controller in a separate method, ex:

    self.navigationItem.leftBarButtonItem = 
        UIBarButtonItem(image:StyleKit.imageOfMap, style:.Plain, target:self, action:"backButtonPressed:");

}

func backButtonPressed(sender:UIButton) {
    navigationController?.popViewControllerAnimated(true)
}



回答2:


Are you looking for something like this?

btn = [UIButton buttonWithType:UIButtonTypeCustom];    
[btn setImage:[UIImage imageNamed:@"YOURIMAGE.png"] forState:UIControlStateNormal];    
btn.frame = CGRectMake(0, 0, 30, 30);
[btn addTarget:self action:@selector(youraction:) forControlEvents:UIControlEventTouchUpInside];  

self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:btn]autorelease];


来源:https://stackoverflow.com/questions/28421769/how-to-replace-customize-back-button-image-in-storyboard-navigationcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!