我想在 UITextView 上选择文本,类似于我们在点击时看到的默认“选择”和“全选”弹出选项。我希望用户能够从我的自定义菜单中做到这一点。我玩了 selectedRange 但这似乎没有奏效。有任何想法吗?
谢谢
我想在 UITextView 上选择文本,类似于我们在点击时看到的默认“选择”和“全选”弹出选项。我希望用户能够从我的自定义菜单中做到这一点。我玩了 selectedRange 但这似乎没有奏效。有任何想法吗?
谢谢
该selectedRange
属性应该这样做,但如文档中所述,仅在 iPhone OS 3.0 及更高版本中。在 2.2 和更早的版本中,selectedRange
属性实际上是一个插入点。
正如在接受的答案中提到的,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];
}
}