使用swift从textview中选择文本后显示副本

时间:2017-09-30 04:23:17

标签: 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
    }
}

1 个答案:

答案 0 :(得分:2)

你需要这样的东西,它唯一的状态问题,如果你的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
    }

}