[英]Add UIBarButtonItem action in Swift programmatically
我試圖以編程方式將動作連接到Swift中的UIBarButtonItem,而沒有任何Storyboard。
我不能這樣:
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)
但是我不太了解如何使用它。 我應該在哪里指出選擇器的名稱?
謝謝!
Swift使我們輕松地向UIBarButtonItem添加動作。
let rightBarButton = UIBarButtonItem()
// add an action
rightBarButton.action = #selector(yourAction)
好的,剛發布此問題之后,我就找到了解決問題的簡便方法……使用“默認” UIBarButtonItem構造函數和以下代碼:
let rightButtonItem = UIBarButtonItem(title: "Camera", style: .Plain, target: self, action: "launchCamera")
rightButtonItem.FAIcon = FAType.Camera
例如,我為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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.