我可以通过编程方式选择 UITextView 中的文本吗?

问题描述 投票:0回答:3

我想在 UITextView 上选择文本,类似于我们点击时看到的默认“选择”和“全选”弹出选项。我希望用户能够从我的自定义菜单中执行此操作。我玩了 selectedRange 但这似乎并没有解决问题。有什么想法吗?

谢谢

iphone select text uitextview highlight
3个回答
6
投票

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


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];
    }
}

0
投票

我只是这样做:

func textViewDidBeginEditing(_ textView: UITextView) {
    textView.selectAll(textView)
}

这似乎工作得很好,并且在我看来添加了一些不错的功能,就像如果你点击现有文本,它会选择全部;如果您点击文本的开头或结尾,它会将光标放在那里而不选择全部(这看起来很自然)。

© www.soinside.com 2019 - 2024. All rights reserved.