UITextView get the current line

后端 未结 3 1136
暖寄归人
暖寄归人 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]);
    
    0 讨论(0)
  • 2021-02-09 04:17

    I ended up using the caretRect method of UITextInput to get the offset from the left. Worked flawlessly.

    0 讨论(0)
  • 2021-02-09 04:20

    This worked for me (self = the UITextView)

    func getLineString() -> String {
        return (self.text! as NSString).substringWithRange((self.text! as NSString).lineRangeForRange(self.selectedRange))
    }
    
    0 讨论(0)
提交回复
热议问题