Regis
Regis

Reputation: 147

Swift - How to show “paste” tooltip menu programmatically?

I'm developing a custom keyboard that send images and I send images by the clipboard, when the user clicks on a image, I want that the "paste" tooltip shows up in the input text field. How I can do that in swift?

Like this: enter image description here

Upvotes: 2

Views: 3233

Answers (2)

Brian Nickel
Brian Nickel

Reputation: 27550

Update

From your question, it looks like you want to show a menu on a text input from a keyboard extension, not in app. There's no API to do this as you're limited to the methods available in UIInputViewController and UITextDocumentProxy, with no access to the app's text field or menu controller. You'll have to provide instructions in your own app or consider creating an iMessage extension instead if that's your target app.


If you want to do this in your own app

There are three parts to this.

First, to show a menu from a text view, it must be the first responder:

textView.becomeFirstResponder()

Second, you need to know the selection's rectangle. Here I'm giving up if there's no caret or selection. We shouldn't about that case because the text view is the first responder.

guard let selectedRange = textView.selectedTextRange else { return }
let selectionLength = textView.offset(from: selectedRange.start to: selectedRange.end)

let targetRect : CGRect
if selectionLength > 0 {
    targetRect = textView.firstRect(for: selectedRange)
} else {
    targetRect = textView.caretRect(for: selectedRange.start)
}

Finally, we can show the menu controller using the shared menu controller:

UIMenuController.shared.setTargetRect(textView.bounds, in: textView)
UIMenuController.shared.setMenuVisible(true, animated: true)

Upvotes: 4

Lou Franco
Lou Franco

Reputation: 89172

There is code in the docs to do it:

https://developer.apple.com/library/content/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/AddingCustomEditMenuItems/AddingCustomEditMenuItems.html

 UIMenuController *theMenu = [UIMenuController sharedMenuController];
 CGRect selectionRect = CGRectMake (currentSelection.x, currentSelection.y, SIDE, SIDE);
 [theMenu setTargetRect:selectionRect inView:self];
 [theMenu setMenuVisible:YES animated:YES];

or in Swift, targeting textField.frame:

 let theMenu = UIMenuController.shared
 theMenu.setTargetRect(textField.frame, inView:self)
 theMenu.setMenuVisible(true, animated: true)

Upvotes: 3

Related Questions