UITextView get the current line

后端 未结 3 1146
暖寄归人
暖寄归人 2021-02-09 03:44

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:

3条回答
  •  花落未央
    2021-02-09 04:04

    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]);
    

提交回复
热议问题