我可以在UITextView中以编程方式选择文本吗?

Sha*_*ief 6 iphone select text highlight uitextview

我想在UITextView上选择Text,类似于我们点击时看到的默认"Select"和"Select All"弹出选项.我希望用户能够从我的自定义菜单中执行此操作.我玩过selectedRange,但似乎没有做到这一点.有任何想法吗?

谢谢

Mar*_*ote 6

selectedRange属性应该这样做,但如文档中所述,仅在iPhone OS 3.0及更高版本中.在2.2及更早版本中,该selectedRange属性实际上是一个插入点.


Har*_*ngh 5

如已接受的答案中所述,selectedRange属性是您需要的东西,但请注意,如果您使用-textViewDidBeginEditing:委托方法,您可能需要推迟一个运行循环以赢得用户生成的“插入”操作:

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