如何限制 swift 中的光标位置?

How to restrict cursor position in swift?

如何使用 caretRectForPosition 方法或任何其他方法限制 swift 中的光标最小位置。假设,我有一个包含一些内容的文本视图,如果用户试图将光标移动到第三个位置之前,它不应该移动。这怎么可能?阅读了几篇关于它的文章,但没有回答我的问题。

我假设通过限制光标的最小位置意味着在示例字符串中:"This is a sample string" - 您要确保用户制作的 selection 在某些 NSRange?

UITextView 有一个委托协议,其中包括 selection 更改时调用的方法:

- (void)textViewDidChangeSelection:(UITextView *)textView

您可以实现委托,侦听此方法,然后执行类似以下操作:

//Swift

func textViewDidChangeSelection(textView: UITextView) {
    let minLocation  = 3
    let currentRange = textView.selectedRange
    if (currentRange.location < minLocation) {
        let lengthDelta = (minLocation - currentRange.location)
        //Minus the number of characters moved so the end point of the selection does not change.
        let newRange = NSMakeRange(minLocation, currentRange.length - lengthDelta);
        //Should use UITextInput protocol
        textView.selectedRange = newRange;
    }
}

//Objective-C

- (void)textViewDidChangeSelection:(UITextView *)textView
{
    NSUInteger minLocation = 3;//your value here obviously
    NSRange currentRange   = textView.selectedRange;
    if (currentRange.location < minLocation) {
        NSUInteger lengthDelta = (minLocation - currentRange.location);
        //Minus the number of characters moved so the end point of the selection does not change.
        NSRange newRange = NSMakeRange(minLocation, currentRange.length - lengthDelta);
        //Should use UITextInput protocol
        UITextPosition *location = [textView positionFromPosition:[textView beginningOfDocument] offset: newRange.location];
        UITextPosition *length   = [textView positionFromPosition:location offset:newRange.length];
        [textView setSelectedTextRange:[textView textRangeFromPosition:location toPosition:length]];
    }
}

您也可以使用类似的方法来施加最大值 selection/length 等

这意味着在之前的示例字符串中,您将无法 select 字符串开头的任何 "Thi"。

在此处了解有关 UITextView 委托的更多信息: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextViewDelegate_Protocol/