iphone - 转到 UITextView 中的特定行

标签 iphone cocoa-touch uitextview

如何告诉 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/

相关文章:

iphone - iPhone 上的 OpenGL ES 1.1 或 2.0

iphone - CLLocationManager 有没有可能被其他应用影响?

iphone - 文本字段方式中的键盘如何向上移动 View

ios - 为什么这个委托(delegate)不适用于 UITextView

ios - 光标消失在UITextView中的键盘下

iphone - 在 iphone 中从数据库中检索图像花费的时间太长

ios - 在 iPhone6 设备上运行我的应用程序时出现错误

iphone - NSURLConnection 未启动

iphone - 如何将我未发布的 iPhone 应用程序提供给不在我附近的人进行测试?

ios - 光标上下移动