开发者

How to get highlighted text of UITextView in UITableViewCell?

开发者 https://www.devze.com 2023-03-10 09:19 出处:网络
I have a custom cell (subclass of UITableViewCell) with a textView inside of it. It works great! Now, when I tap on a cell and highlight some text, the default UIMenuController appears and I can choos

I have a custom cell (subclass of UITableViewCell) with a textView inside of it. It works great! Now, when I tap on a cell and highlight some text, the default UIMenuController appears and I can choose to copy the highlighted text. Also this function works perfectly. Now, I would like to add a custom button to the U开发者_C百科IMenuController, which I actually did, but to perform the menu item action I need to know what the selected text is. How can I get it?


To explain this better, there is no method in UITextField that allows us to know what the currently selected text is. But we can leverage the copy action on the text field that is associated with the menu controller. The copy action copies the text onto the pasteboard which we will need to retrieve. I was able to implement a Log function in my custom subclass of UITextField like this –

- (void)log:(id)sender {
    [self copy:sender];
    NSString *highlightedText = [UIPasteboard generalPasteboard].string;
    NSLog(@"%@", highlightedText);
}

This logs the selected text onto the console. Doesn't do much but gives you the basic idea.

0

精彩评论

暂无评论...
验证码 换一张
取 消