ios - 使用 swift 从 TextView 中选择文本后显示副本

标签 ios swift uitextview uimenucontroller

enter image description here

使用此代码,它将向我显示:复制、选择、全选和粘贴。

但我想当用户单击选择时先选择并选择全部,然后显示复制,当单击复制时显示粘贴。

class CustomTextField: UITextView
{
    override public func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool
    {

        if action == #selector(select(_:)) || action == #selector(copy(_:)) || action == #selector(selectAll(_:)) || action == #selector(paste(_:))
        {
            return true
        }
        return false
    }
}

最佳答案

你需要这样的东西,它只是状态的问题,如果你的 currentState 是你应该在菜单中显示的东西,你还需要重写这些方法中的每一个来更改当前状态

import UIKit

enum MenuState{
    case select
    case copy
    case paste
}

class CustomTextField: UITextField {

    var currentState : MenuState = .select

    override public func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool
    {
        switch self.currentState {
        case .select:
            if action == #selector(select(_:)) || action == #selector(selectAll(_:)){
                return true
            }
        case .copy:
            if action == #selector(copy(_:)){
                return true
            }
        case .paste:
            if action == #selector(paste(_:)){
                return true
            }
        }
        return false
    }

    override func select(_ sender: Any?) {
        super.select(sender)
        self.currentState = .copy
    }

    override func selectAll(_ sender: Any?) {
        super.selectAll(sender)
        self.currentState = .copy
    }

    override func copy(_ sender: Any?) {
        super.copy(sender)
        self.currentState = .paste
    }

    override func paste(_ sender: Any?) {
        super.paste(sender)
        self.currentState = .select
    }

}

关于ios - 使用 swift 从 TextView 中选择文本后显示副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46499551/

相关文章:

ios - swift 2.1 无法将 anyobject 类型的值转换为预期的参数类型 nslayoutconstraint

ios - 如何将富文本粘贴到 UITextView 中?

ios - UITextView/UITextField 中的格式化文本/标签

ios - 从 XML 文件 iOS 中消除重复的配置文件

ios - 当首先加载 gameScene 时可以工作,但是当被另一个场景加载时播放半秒并立即停止(没有错误),为什么?

ios - 过滤 View 在点击时会导致详细 View 不正确,但在滑动时会导致详细 View 正确

Android 相当于 textViewShouldBeginEditing

ios - "Communications error"- AVFoundation 相机

ios - 从 Parse 中的指针访问另一个类列

swift - Xcode 编译器错误未在编辑器中突出显示