在UTextView中每次移动光标一个字 [英] Move Cursor One Word at a Time in UTextView
本文介绍了在UTextView中每次移动光标一个字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个按钮,在UITextView中一次移动光标位置一个字。从用户的角度来看,这将与Mac OS X中的Option-Right Arrow相同,后者被定义为转到插入点右侧的词。
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);
}
感谢任何建议。
推荐答案
能够像这样实现
- (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);
}
}
这篇关于在UTextView中每次移动光标一个字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文