[英]how to get share button to work in tableview cell swift?
我是 swift 的新手,我正在使用 tableviews 創建提要。 我有一個帶有按鈕的自定義表格視圖單元格,並且當在單元格上點擊按鈕時,我已經包含了一個 IBAction function。
@IBAction func didTapShareBtn(_ sender: Any) {
// display share screen with url
}
您不想嘗試從您的單元格內部顯示共享屏幕。
推薦的方法是使用closure
,這樣您的單元格就可以告訴 controller 該按鈕已被點擊,並且 controller 將處理該操作。
快速示例 - 假設您有一個帶有 Label 和按鈕的單元格:
class FeedListTableViewCell: UITableViewCell {
var btnTapClosure: ((FeedListTableViewCell)->())?
@IBOutlet var theLabel: UILabel!
@IBAction func didTapShareButton(_ sender: Any) {
// tell the controller the button was tapped
btnTapClosure?(self)
}
}
當您的表視圖 controller 將單元格出列時,我們設置 label 文本並設置關閉:
class FeedTableViewController: UITableViewController {
var myData: [String] = [
"https://apple.com",
"https://google.com",
"https://stackoverflow.com",
]
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FeedCell", for: indexPath) as! FeedListTableViewCell
cell.theLabel.text = myData[indexPath.row]
// set the closure
cell.btnTapClosure = { [weak self] cell in
// safely unwrap weak self and optional indexPath
guard let self = self,
let indexPath = tableView.indexPath(for: cell)
else { return }
// get the url from our data source
let urlString = self.myData[indexPath.row]
guard let url = URL(string: urlString) else {
// could not get a valid URL from the string
return
}
// present the share screen
let objectsToShare = [url]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
self.present(activityVC, animated: true, completion: nil)
}
return cell
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.