简体   繁体   中英

Add UIBarButtonItem action in Swift programmatically

I'm trying to connect an action to my UIBarButtonItem in Swift, programmatically, without any Storyboard.

I can't do it this way :

var b = UIBarButtonItem(title: "Continue", style: .Plain, target: self, action: "sayHello")

Since I use an external library ( Font_Awesome_Swift ) which doesn't have a constructor to create an UIBarButtonItem with an icon from the library. So I'm doing it this way :

let rightButtonItem = UIBarButtonItem()
rightButtonItem.FAIcon = FAType.FACamera

Then, I want to be able to attach an action to this UIBarButtonItem. I have found in another answer, this solution :

UIApplication.sharedApplication().sendAction(barButtonItem.action, to: barButtonItem.target, from: self, forEvent: nil)

But I don't really understand how to use it. Where should I indicate the name of the selector ?

Thanks!

Swift makes adding an action to a UIBarButtonItem easy for us.

let rightBarButton = UIBarButtonItem()
// add an action
rightBarButton.action = #selector(yourAction)

Ok, just after posting this question, I have found an easy way to solve my issue... With the "default" UIBarButtonItem constructor and the following code :

let rightButtonItem = UIBarButtonItem(title: "Camera", style: .Plain, target: self, action: "launchCamera")
rightButtonItem.FAIcon = FAType.Camera

for example i write this code for UIBarButtonItem:

 navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action , target: self, action: #selector(shareTapped))

and selector code is :

func shareTapped() {

//         for share in Social media or Save in local
//        let vc = UIActivityViewController(activityItems: [imageView.image!], applicationActivities: [])
//        vc.popoverPresentationController?.barButtonItem = navigationItem.rightBarButtonItem
//        present(vc, animated: true)


        // this line its for share photo in facebook or twitter
        if let vc = SLComposeViewController(forServiceType:  SLServiceTypeTwitter) {
            vc.setInitialText("Look at this great picture!")
            vc.add(imageView.image!)
            vc.add(URL(string: "http://www.photolib.noaa.gov/nssl"))
            present(vc, animated: true)
        }
    }

and i use image in my app and because of this i using image view.image

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM