I am new to swift and i am creating a feed using tableviews. I have a custom table view cell which has a button and i have included a IBAction function for when the button is tapped on the cell.
@IBAction func didTapShareBtn(_ sender: Any) {
// display share screen with url
}
You don't want to try and present a share screen from inside your cell.
The recommended approach is to use a closure
so your cell can tell the controller that the button was tapped, and the controller will handle the action.
Quick example - assuming you have a cell with a Label and a Button:
class FeedListTableViewCell: UITableViewCell {
var btnTapClosure: ((FeedListTableViewCell)->())?
@IBOutlet var theLabel: UILabel!
@IBAction func didTapShareButton(_ sender: Any) {
// tell the controller the button was tapped
btnTapClosure?(self)
}
}
When your table view controller dequeues the cell, we set the label text and we set the closure:
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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.