Home > Software design >  How to programmatically detect the use of text menu in iOS [Swift 5]
How to programmatically detect the use of text menu in iOS [Swift 5]

Time:07-17

I want to record the user's behavior on a UITextViewer. Specifically, I want to programmatically capture when the user tapped text menu functions such as copy, cut, translate, select all, look up.

This question (How can I detect that a user has tapped a formatting button in a UIMenuController?) seems to be the closest one, but I want to know the code for Swfit instead of Object-c.

How can I observe when the user tapped a specific text menu? I would also like to know which words were selected when a specific menu was called.

CodePudding user response:

Here some code to not have paste in menu when selected text contains a certain String ("XXX") :

override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    let canPerformAction = super.canPerformAction(action, withSender: sender)
    
    // Next line can help you find menu action names
    print("canPerformAction:\(action):sender:\(String(describing: sender))=\(canPerformAction)")

    let pasteAction = NSSelectorFromString("paste:")
    
    if canPerformAction && action == pasteAction {
        // Set true/false based on your requirement
        // Check for current selected text
        let range = self.selectedRange
        guard let swiftRange = Range(range, in: self.text) else {return false}
        let selectedText = self.text[swiftRange]
        if selectedText.contains("XXX") {
            return false
            
        }
        return true
    }
    
    
    return canPerformAction
}

The action is computed each time the menu appears. So if you change selection, the check is again done and the paste command may be there or not. Hope this can help you,

  • Related