您不想尝试从您的单元内部展示共享屏幕。
推荐的方法是使用closure,这样您的单元格就可以告诉控制器该按钮已被点击,控制器将处理该操作。
快速示例 - 假设您有一个带有标签和按钮的单元格:
class FeedListTableViewCell: UITableViewCell {
var btnTapClosure: ((FeedListTableViewCell)->())?
@IBOutlet var theLabel: UILabel!
@IBAction func didTapShareButton(_ sender: Any) {
// tell the controller the button was tapped
btnTapClosure?(self)
}
}
当您的表格视图控制器使单元格出列时,我们设置标签文本并且我们设置闭包:
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
}
}