我在 NSTextView 控件中放置了一些文字。好吧,我的文本字符串来自哪里并不重要。所以我不会仅将此主题限制为OSX。无论如何,我可以找到所选字符串的当前位置,如...
NSRange sel = [textView1 selectedRange]; // textView1 may be NSTextView or UITextView.
NSNumber *point = [NSNumber numberWithInteger:sel.location];
如何找出此选定字符串属于哪一行?
NSArray *array = [[textView1 string] componentsSeparatedByString:@"\r\n"];
感谢您的帮助。
答案 0 :(得分:2)
我认为以下代码应该这样做。 m是所选字符串所属的行号。它基于一个数组。所以第一行是0,而不是1. stringContains只是一个函数,用于查看字符串(在这种情况下,每行)是否包含所选的段落。对于我需要返回的简单数字,有很多行代码。我不知道这是否是一种更简单的方法。请注意,m的数据类型设置为“unsigned”,k设置为“unsigned long”。 k是所有字符的数量。此数字和stringContains确保m是所选段落所属的行。如果总行数大到几千,则可能必须自动释放变量。那是OSX。
- (void)findLineNumber {
NSRange sel = [textView1 selectedRange];
NSNumber *point = [NSNumber numberWithInteger:sel.location];
NSString *selectedText = [[textView1 string] substringWithRange:[textView1 selectedRange]]; // [textView1 string] into textView1.text for iOS
NSArray *array = [[textView1 string] componentsSeparatedByString:@"\n"]; // [textView1 string] into textView1.text for iOS
unsigned long k = 0;
unsigned m;
for (unsigned i2 = 0; i2 < array.count; i2++) {
NSString *line = [array objectAtIndex:i2];
if (point.integerValue >= k && [self stringContains:line:selectedText]) {
m = i2;
}
k += line.length;
}
NSLog(%i,m); // zero-based
}
- (BOOL)stringContains:(NSString *)source :(NSString *)find {
// case-sensitive
NSRange myRange;
myRange = [source rangeOfString:find];
if ([source isEqualToString:find]) {
return true;
} else {
if (source.length > find.length) {
if (myRange.location == NSNotFound) {
return false;
}
else {
return true;
}
} else {
return false;
}
}
}
答案 1 :(得分:1)
你当然不应该使用componentsSeparatedByString:@"\r\n”
,只需使用\ n。本机文本对象不使用CRLF,只使用LF。
另请注意,示例中的sel.location只是选择的开头 - 如果选择了多个字符,我不确定您要执行的操作。
无论如何,你可能想打电话:
- (void)getLineStart:(NSUInteger *)startIndex end:(NSUInteger *)lineEndIndex contentsEnd:(NSUInteger *)contentsEndIndex forRange:(NSRange)aRange
Parameters
startIndex
Upon return, contains the index of the first character of the line containing the beginning of aRange. Pass NULL if you do not need this value (in which case the work to compute the value isn’t performed).
lineEndIndex
Upon return, contains the index of the first character past the terminator of the line containing the end of aRange. Pass NULL if you do not need this value (in which case the work to compute the value isn’t performed).
contentsEndIndex
Upon return, contains the index of the first character of the terminator of the line containing the end of aRange. Pass NULL if you do not need this value (in which case the work to compute the value isn’t performed).
aRange
A range within the receiver. The value must not exceed the bounds of the receiver.
Raises an NSRangeException if aRange is invalid.