使 UIMenuController 能够在 TextField 中进行复制和粘贴而不使文本字段可编辑 isUserInteractionEnabled = false

问题描述

我有 textfield.isUserInteractionEnabled = false 的文本字段,但我希望在文本字段中启用复制和粘贴功能,以便用户在其上选择时,它可以打开菜单进行复制,有没有办法做到?

谢谢

解决方法

我用 tableView 找到了解决方案:

func tableView(_ tableView: UITableView,shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView,canPerformAction action: Selector,forRowAt indexPath: IndexPath,withSender sender: Any?) -> Bool {
    if (action == #selector(UIResponderStandardEditActions.copy(_:))) {
        return true
    }

    return false
}

func tableView(_ tableView: UITableView,performAction action: Selector,withSender sender: Any?) {
    if let cell = tableView.cellForRow(at: indexPath) {
        UIPasteboard.general.string = cell.textLabel?.text
    }
}