Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting bar button item image to system item programmatically—Swift

I have a bar button item set to a custom image from my image assets folder. After launch, once the user presses the button, I want it to change to a system item—the stop (X) button. I know how to programmatically change the image of the bar button, but how do I change the image to one of the system items in my code?

Swift 3, Xcode 8 beta 1.

Edit Here are the system items I'm referencing: Xcode system items

How can I change my button's image to one of those system items from my code?

like image 773
owlswipe Avatar asked Jul 18 '16 16:07

owlswipe


2 Answers

navigationItem.rightBarButtonItem = UIBarButtonItem(
    barButtonSystemItem: UIBarButtonItem.SystemItem.add, 
    target: self, 
    action: #selector(yourMethod)
)

Change 'add' according to https://developer.apple.com/documentation/uikit/uibarbuttonitem/systemitem

like image 118
blanNL Avatar answered Oct 06 '22 00:10

blanNL


For those of you using iOS 13 & up, you can use the UIImage(systemName:) property. You can search the systemItem names and corresponding images using Apple's SF Symbols app. Here's an example using the stop X button:

barButtonItem.image = UIImage(systemName: "xmark")
like image 28
Michael Avatar answered Oct 06 '22 01:10

Michael