我想在 UITextView 上选择文本,类似于我们点击时看到的默认“选择”和“全选”弹出选项。我希望用户能够从我的自定义菜单中执行此操作。我玩了 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];
}
}
我只是这样做:
func textViewDidBeginEditing(_ textView: UITextView) {
textView.selectAll(textView)
}
这似乎工作得很好,并且在我看来添加了一些不错的功能,就像如果你点击现有文本,它会选择全部;如果您点击文本的开头或结尾,它会将光标放在那里而不选择全部(这看起来很自然)。