Search code examples
iosswiftiphoneuibarbuttonitemuibarbuttonsystemitem

Programattically set barbutton " System Item"


I want to set share button on rightbarbuttonitem of navigation controller. I don't want to add custom images , I want use share button image provided by Xcode.This is how I do in storyboard. I set Style , and set System_Item as Action.

enter image description here

enter image description here

Now the question is how do I set System_Item programatically, if I create barbuttonitem programatically ?

let shareButton = UIBarButtonItem(title: "",
                                  style: .plain,
                                  target: self,
                                  action: #selector(shareAction(sender:)))
    shareButton.tintColor = AppColor.barButtonColor

    navigationItem.rightBarButtonItem = shareButton

Solution

  • you need to use UIBarButtonSystemItemAction option to get share action directly

       let share = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareAction(sender:)))
        shareButton.tintColor = AppColor.barButtonColor
        navigationItem.rightBarButtonItem = share
    

    and handle the action as like

    @objc func shareAction(sender: UIBarButtonItem) {
    
    }