【问题标题】:Can I Programmatically Select Text in UITextView?我可以在 UITextView 中以编程方式选择文本吗?
【发布时间】:2011-02-07 17:32:55
【问题描述】:

我想在 UITextView 上选择 Text,类似于我们在点击时看到的默认“选择”和“全选”弹出选项。我希望用户能够从我的自定义菜单中做到这一点。我玩了 selectedRange 但这似乎没有奏效。有什么想法吗?

谢谢

【问题讨论】:

  • 你能把代码贴在你尝试使用selectedRange的地方吗?这听起来像是正确的方法。您可能给它一个无效的范围或其他东西。
  • 我遇到了同样的问题。我能够获得要选择的文本的正确范围(UITextView 滚动到正确的位置),但是该范围内的文本没有“突出显示”,也没有插入点。我想知道是否需要先向 UITextView 发送消息以“激活”或其他什么?

标签: iphone select text uitextview highlight


【解决方案1】:

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

【讨论】:

  • 请注意,创建NSRange 的函数是NSMakeRange(),而不是您所期望的NSRangeMake()。
【解决方案2】:

正如接受的答案中提到的,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];
    }
}

【讨论】:

    猜你喜欢
    • 2012-02-15
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多