UITextView - 粘贴操作在iOS 11上插入空字符串

rrp*_*inc 6 copy-paste uitextview ios

我有一个常规UITextView的开箱即用的粘贴支持UIKit.textView中没有任何花哨的东西.直到iOS 10,包括,粘贴按预期工作.

从iOS 11开始,当我使用UIMenuController动作将文本粘贴到其中时,没有任何文本正在UIMenuController贴上(点击粘贴后消失).

调试UITextViewDelegate方法:

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

显示一个空字符串即将插入,虽然PasteBoard有一个非空值,但我无法弄清楚为什么.

但是,从Safari的地址栏复制URL时,粘贴操作会起作用.

-

我知道Apple对iOS 11中的粘贴功能进行了更改,但是,根据Cut-Copy-Paste Apple Docs,UITextView粘贴功能应该保持不变.

iOS 11还推出了一款UITextPasteDelegate.我设法使用它修复了粘贴操作的工作修复,但这不是想要的方法:

UITextPasteDelegate在包含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]];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

顺便说一下,将文本粘贴到文本中也是如此UISearchBar.

我的项目使用iOS 9.0作为其部署目标.我没有愚弄第一响应链或搞砸了它们.

-

如果我打开一个新项目并使用相同的UITextView功能,粘贴按预期工作,而不需要hacky修复.