Search code examples
iosswiftcursoruitextview

How to restrict cursor position in swift?


How to restrict the cursor minimum position in swift using caretRectForPosition method or any other method. Suppose, I have a textview with some content and if the user is trying to move the cursor before 3rd position it should not move. How's this possible? Read few articles on it but doesn't answer to my problem.


Solution

  • Am making an assumption that by restricting the cursor minimum position you mean that out of a sample string: "This is a sample string" - you want to ensure that the selection made by the user is within a certain NSRange?

    UITextView has a delegate protocol that includes a method called when the selection changes:

    - (void)textViewDidChangeSelection:(UITextView *)textView
    

    You could implement the delegate, listen for this method and then do something like:

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

    You could also use similar approach to impose a max selection/length etc.

    This would mean that on the sample string earlier you would not be able to select any of the "Thi" at the beginning of the string.

    More info on UITextView delegate here: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextViewDelegate_Protocol/