Can I Programmatically Select Text in UITextView?

强颜欢笑 提交于 2020-01-12 05:46:26

问题


I want to select Text on UITextView, similar to the default "Select" and "Select All" pop options we see when we tap. I want to the user the ability to do that from my custom menu. I played with selectedRange but that doesnt seem to do the trick. Any ideas?

Thanks


回答1:


The selectedRange property should do it but, as mentioned in the documentation, only in iPhone OS 3.0 and later. In 2.2 and earlier, the selectedRange property is actually an insertion point.




回答2:


As mentioned in the accepted answer, the selectedRange property is the thing you need, but beware that if you are using the -textViewDidBeginEditing: delegate method you might need to defer one run loop in order to win out over the user generated "insertion" action:

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    // Look for the default message and highlight it if present
    NSRange defaultMsgRange = [textView.text rangeOfString:NSLocalizedString(@"TEXTFIELD_DEFAULT_MESSAGE", nil) options:NSAnchoredSearch];

    BOOL isDefaultMsg = !(defaultMsgRange.location == NSNotFound && defaultMsgRange.length == 0);
    if (isDefaultMsg) {

        // Need to delay this by one run loop otherwise the insertion wins
        [self performBlock:^(id sender) {  // (BlocksKit - use GCD otherwise)

            textView.selectedRange = defaultMsgRange;

        } afterDelay:0.0];
    }
}


来源:https://stackoverflow.com/questions/2634425/can-i-programmatically-select-text-in-uitextview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!