[英]Add UIBarButtonItem action in Swift programmatically
I'm trying to connect an action to my UIBarButtonItem in Swift, programmatically, without any Storyboard. 我试图以编程方式将动作连接到Swift中的UIBarButtonItem,而没有任何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. 由于我使用的是外部库(
Font_Awesome_Swift
),该库没有构造函数来使用该库中的图标创建UIBarButtonItem。 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. 然后,我希望能够将一个动作附加到此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. Swift使我们轻松地向UIBarButtonItem添加动作。
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 : 好的,刚发布此问题之后,我就找到了解决问题的简便方法……使用“默认” UIBarButtonItem构造函数和以下代码:
let rightButtonItem = UIBarButtonItem(title: "Camera", style: .Plain, target: self, action: "launchCamera")
rightButtonItem.FAIcon = FAType.Camera
for example i write this code for UIBarButtonItem: 例如,我为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 我在我的应用程序中使用图像,因此我使用图像view.image
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.