Mili Mili - 3 years ago 248
iOS Question

Display copy after select text from textview using swift

enter image description here

Using this code it will show me : copy, select, select all and paste.

But I want select and select all first when user click on select then and then copy will display and when click on copy then paste will display.

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
}
}

Answer Source

You need something like this, its only matters of states, if your currentState is one you should show something in the menu, you also need override each of those methods to change the current state

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
    }

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download