以编程方式在Swift中添加UIBarButtonItem操作

时间:2016-02-29 15:56:42

标签: ios swift swift2 uibarbuttonitem

我试图以编程方式在Swift中将动作连接到我的UIBarButtonItem,而不使用任何故事板。

我不能这样做:

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

因为我使用的外部库(Font_Awesome_Swift)没有构造函数来创建带有库中图标的UIBarButtonItem。所以我这样做:

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

然后,我希望能够将动作附加到此UIBarButtonItem。我在另一个答案中找到了这个解决方案:

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

但我真的不懂如何使用它。我应该在哪里指出选择器的名称?

谢谢!

3 个答案:

答案 0 :(得分:1)

好的,在发布此问题之后,我找到了解决问题的简单方法......使用“默认”UIBarButtonItem构造函数和以下代码:

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

答案 1 :(得分:1)

Swift为我们添加了一个对UIBarButtonItem很容易的动作。

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

答案 2 :(得分:0)

例如我为UIBarButtonItem写了这段代码:

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

和选择器代码是:

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)
        }
    }

我在我的应用程序中使用图像,因此我使用图像view.image