UITextView获取当前行 [英] UITextView get the current line

查看:219
本文介绍了UITextView获取当前行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法(疯狂的黑客欢迎)将当前行作为UITextView的字符串?这将包括自动换行等。例如,在这种情况下:

Is there a way (crazy hacks welcome) to get the current line as a string of a UITextView? This would include word wrapping, etc. For example, in this case:

该方法将返回堆栈溢出。这不是很好吗?我因为这是基于当前行的光标。

The method would return "stack overflow. Isn't it great? I" because that is the current line based on the cursor.

它还可以根据光标的位置返回这是我为之做的测试或这样做。我尝试使用UITextView方法和UITextInput协议。

It could also return "This is a test I made for" or "think so", based on the position of the cursor. I have tried working with both the UITextView methods and those of UITextInput protocol.

编辑:

这是我尝试使用的代码。我需要找到字符串的原因是为了得到它的长度,所以这就是为什么你会看到基于UI的代码。

Here is the code I have attempted to use. The reason I need to find the string is to get it's length, so this is why you'll see UI based code.

NSRange location = self.textView.selectedRange;
NSString *searchString = [self.textView.text substringWithRange:NSMakeRange(0, location)];
CGSize currentStringDimensions = [searchString sizeWithFont:self.textView.font constrainedToSize:CGSizeMake(self.textView.frame.size.width, self.textView.frame.size.height) lineBreakMode:NSLineBreakByWordWrapping];    
float numberOfRows = (currentStringDimensions.width/(self.textView.frame.size.width));
float left = (float)(numberOfRows - (int)numberOfRows) * (self.textView.frame.size.width);

然而,这不起作用。我认为它可能会包含单词或不同大小的字符,但左边的值不一致或在第一行后关闭。

This doesn't work, however. I think it might have something to with words being wrapped or the differently sized characters, but the left value is inconsistent or off after the first line.

推荐答案

以下代码解决方案似乎正在运行。此代码中的self指的是 UITextView 的实例。

The following code solution seem to be working. The "self" in this code refers to an instance of UITextView.

- (NSString *) getLineString:(NSRange)range
{
    NSLayoutManager *manager = self.layoutManager;

    // Convert it to a glyph range
    NSRange matchingGlyphRange = [manager glyphRangeForCharacterRange:range actualCharacterRange:NULL];

    // line fragment rect at location range
    CGRect rect = [manager lineFragmentRectForGlyphAtIndex:matchingGlyphRange.location effectiveRange:nil];

    // obtain the line range for the line fragment rect
    NSRange lineRange = [manager glyphRangeForBoundingRect:rect inTextContainer:self.textContainer];

    // extract the string out from lineRange
    return [self.text substringWithRange:lineRange];
}

// ... later
NSLog(@"line %@", [self getLineString:self.selectedRange]);

这篇关于UITextView获取当前行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆