4

我想创建一个按钮,一次移动一个单词在 UITextView 中的光标位置。从用户的角度来看,这与 Mac OS X 中的 Option-Right Arrow 相同,被定义为“转到插入点右侧的单词”。

我找到了几种方法来一次移动角色。您将如何修改它以一次移动一个单词?

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

感谢您的任何建议。

4

1 回答 1

8

能够像这样实现它,

- (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);
    }

}
于 2011-06-08T02:09:24.250 回答