[英]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.