Move Cursor One Word at a Time in UTextView

会有一股神秘感。 提交于 2019-12-07 07:52:52

问题


I would like to create a button that moves the cursor position in a UITextView one word at a time. From a user perspective, this would be the same as Option-Right Arrow in Mac OS X, which is defined as "go to the word to the right of the insertion point."

I have found a couple ways to move on character at a time. How would you modify this to move one word at a time?

- (IBAction)rightArrowButtonPressed:(id)sender
{
     myTextView.selectedRange = NSMakeRange(myTextView.selectedRange.location + 1, 0); 
}

Thanks for any suggestions.


回答1:


Was able to implement it like this,

- (IBAction)nextWord {
    NSRange selectedRange = self.textView.selectedRange;
    NSInteger currentLocation = selectedRange.location + selectedRange.length;
    NSInteger textLength = [self.textView.text length];

    if ( currentLocation == textLength ) {
        return;
    }

    NSRange newRange = [self.textView.text rangeOfCharacterFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]
                                                           options:NSCaseInsensitiveSearch
                                                             range:NSMakeRange((currentLocation + 1), (textLength - 1 - currentLocation))];
    if ( newRange.location != NSNotFound ) {
        self.textView.selectedRange = NSMakeRange(newRange.location, 0);
    } else {
        self.textView.selectedRange = NSMakeRange(textLength, 0);
    }
}

- (IBAction)previousWord {
    NSRange selectedRange = self.textView.selectedRange;
    NSInteger currentLocation = selectedRange.location;

    if ( currentLocation == 0 ) {
        return;
    }

    NSRange newRange = [self.textView.text rangeOfCharacterFromSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]
                                                           options:NSBackwardsSearch
                                                             range:NSMakeRange(0, (currentLocation - 1))];
    if ( newRange.location != NSNotFound ) {
        self.textView.selectedRange = NSMakeRange((newRange.location + 1), 0);
    } else {
        self.textView.selectedRange = NSMakeRange(0, 0);
    }

}


来源:https://stackoverflow.com/questions/6273323/move-cursor-one-word-at-a-time-in-utextview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!