Is there a simple way for subclasses of UITableViewCell to show the \'Copy\' UIMenuController popup like in the Address book app (see screenshot), after the selection is hel
created 2 scenarios out of Alexander's Code:
1.in case you want to copy textLabel and not detailTextLabel just use this code:
//MARK: Delegate
func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
return (tableView.cellForRow(at: indexPath)?.textLabel?.text) != nil
}
func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return action == #selector(copy(_:))
}
func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
if action == #selector(copy(_:)) {
let cell = tableView.cellForRow(at: indexPath)
let pasteboard = UIPasteboard.general
pasteboard.string = cell?.textLabel?.text
}
}
2.if you have customCell with customLabels and you want to copy all customLabels text Do this:
//MARK: Delegate
func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
return (tableView.cellForRow(at: indexPath) != nil)
}
func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return action == #selector(copy(_:))
}
func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
if action == #selector(copy(_:)) {
/* change these array names according to your own array names */
let customlabel1 = customlabel1Array[indexPath.row]
let customlabel2 = customlabel2Array[indexPath.row]
let customlabel3 = customlabel3Array[indexPath.row]
let pasteboard = UIPasteboard.general
pasteboard.string = "\(customlabel1)\n\(customlabel2)\n\(customlabel3)" /* \n is for new line. */
}
}
}
By the way you should set your tableView delegate to self in viewDidLoad for these to work, like this:
override func viewDidLoad() {
yourTableView.delegate = self
}