UITextView - Paste action inserts empty string on iOS 11

Viewed 1593

I have a regular UITextView that has Paste support out of the box via UIKit. Nothing fancy in the textView. Up until iOS 10, including, paste worked as expected.

As of iOS 11 when I paste text into it using the UIMenuController action, no text is being paster (The UIMenuController disappears after tapping on paste).

Debugging the UITextViewDelegate's method:

- (BOOL)textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text,

shows an empty string is about to be inserted, although the PasteBoard has a non empty value, but I can't figure out why.

However, when copying the url from Safari's address bar, the paste action works.

--

I know Apple made changes to the Paste functionality in iOS 11, however, according to the Cut-Copy-Paste Apple Docs, UITextView's paste functionality should remain the same.

iOS 11 also introduced a UITextPasteDelegate. I managed to hack a working fix for the Paste action using it but this doesn't feel like the way to go:

declare implementation of UITextPasteDelegate and do the following in the class/controller holding your UITextView:

//declare yourself as a paste delegate
- (void)viewDidLoad {
    [super viewDidLoad];
    self.textView.pasteDelegate = self;
}

//Set a Hook to know there's a paste action while I'm the first responder - fired when Paste was tapped
- (void)textPasteConfigurationSupporting:(id<UITextPasteConfigurationSupporting>)textPasteConfigurationSupporting transformPasteItem:(id<UITextPasteItem>)item API_AVAILABLE(ios(11.0)) {
    [self paste:textPasteConfigurationSupporting];
}

//generic paste action handler
- (void)paste:(id)sender {
    UIPasteboard *gpBoard = [UIPasteboard generalPasteboard];
    if ([gpBoard hasStrings]) {
        id<UITextPasteConfigurationSupporting> pasteItem = (id<UITextPasteConfigurationSupporting>)sender;
        if ([pasteItem isKindOfClass:[UITextView class]]) {
            UITextView* myTextView = (UITextView*)pasteItem;
                [myTextView insertText:[gpBoard string]];
        }
    }
}

BTW, the same goes for pasting text into a UISearchBar.

My project uses iOS 9.0 as it's deployment target. I did not fool around with first-responder chains or messed them up.

--

If I open a new project and use the same UITextView functionality, paste works as expected without the hacky fix.

0 Answers
Related