如何告诉 UITextView 在出现时将光标设置到特定行(例如第 13 行)?
最佳答案
UITextView 有一个方法 setSelectedRange: (NSRange) 范围。
如果您知道第 13 行出现在字符串中的位置,例如位置 237,则执行: [textView setSelectedRange: NSMakeRange(237,0)];
如果您需要找出第 13 行出现的位置,则需要做更多的工作。我首先查看 sizeWithFont,记住将 textView 的宽度缩小大约 16 个磅,以便 iOS 得到正确的总和。 (也就是说,如果有换行符,则只需找到第 13 个(或第 n 个)“\n”的位置即可。)
更新您在评论中进一步询问
有很多方法可以找到第 n 个\n 的位置。下面的代码片段不太漂亮,但它可以完成工作。您还可以使用 rangeOfString 并迭代“\n”。在此代码片段中,如果目标行大于行数,则会将光标置于末尾。这里的代码假设您有一个名为 userEntry 的 UITextView 属性。
int targetLine = 3; // change this as appropriate 0=first line
NSRange range;
NSString* exampleString = @"Hello there\nHow is it going?\nAre you looking for a new line?\nA new line in what?\nThat remains to be seen";
NSArray* separateLines = [exampleString componentsSeparatedByString:@"\n"];
if (targetLine < [separateLines count])
{
int count = 0;
for (int i=0; i<targetLine; i++)
{
count = count + [[separateLines objectAtIndex:i] length] + 1; // add 1 to compensate \n separator
}
range = NSMakeRange(count, 0);
}
else
{
range = NSMakeRange([exampleString length], 0); // set to the very end if targetLine is > number of lines
}
[[self userEntry] setText: exampleString];
[[self userEntry] setSelectedRange:range];
[[self userEntry] becomeFirstResponder];
关于iphone - 转到 UITextView 中的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6644218/