UITextView中的自动换行检测 [英] Word wrap detecting in UITextView

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

问题描述

我正在通过扩展UITextView来实现自定义的RTF编辑器.当用户选择文本范围并使用突出显示"菜单时,编辑器将为所选文本绘制蓝色背景:

I am implementing a customized rich text editor by extending the UITextView. When user selects the text range and apples the 'highlighting' menu, the editor will draw a blue background for the selected text:

- (CGRect)getRectAtRangePos:(NSInteger)pos {
    UITextPosition *beginning = self.beginningOfDocument;
    UITextPosition *start = [self positionFromPosition:beginning offset:pos];
    CGRect rect = [self caretRectForPosition:start];
    return [self convertRect:rect fromView:self.textInputView];
}


- (void)drawRange:(NSRange)range {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 0x16/255.f, 0x38/255.f, 0xfc/255.f, 0.5);
    CGRect startRect = [self getRectAtRangePos:range.location];
    CGRect endRect = [self getRectAtRangePos:range.location + range.length];

    CGFloat padding = 1;
    CGFloat margin = 1;

    if (ABS(endRect.origin.y - startRect.origin.y) < 5) {//They are in the same line
        CGRect wholeRect = CGRectMake(startRect.origin.x, startRect.origin.y + padding, endRect.origin.x - startRect.origin.x, startRect.size.height - 2 * padding);
        CGContextFillRect(context, wholeRect);
    }
    else {//The range occupies at least two lines
        CGRect firstRect = CGRectMake(startRect.origin.x, startRect.origin.y + padding, self.bounds.size.width - startRect.origin.x - margin, startRect.size.height - 2 * padding);
        CGContextFillRect(context, firstRect);
        CGFloat heightDiff = endRect.origin.y - (startRect.origin.y + startRect.size.height);
        if (heightDiff > 5) {//The range occupies more than two lines
            CGRect secondRect = CGRectMake(margin, startRect.origin.y + startRect.size.height + padding, self.bounds.size.width - 2*margin, heightDiff - 2* padding);
            CGContextFillRect(context, secondRect);
        }
        CGRect thirdRect = CGRectMake(margin, endRect.origin.y + padding, endRect.origin.x, endRect.size.height - 2* padding);
        CGContextFillRect(context, thirdRect);
    }
}

当所选文本中包含这引起了单词环绕一个长型字,该蓝色背景看起来难看.

When the selected text contains a long word which caused the word wrap, the blue background looks ugly.

有没有一种方法可以检测自动换行的位置?谢谢!

Is there a way to detect the position where the word wrap? Thanks!

推荐答案

好的,最后我解决了这个问题. 要检测自动换行或换行符,使用以下代码很简单:

OK, finally I solved this problem. To detecting the word wrap or a new line break, it's simple to use following code:

#pragma UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
    if ( ABS(lastContentSize_.height - textView.contentSize.height) > 1) {
        NSLog(@"word wrap or line break!");
    }

}

仅此而已:)

这篇关于UITextView中的自动换行检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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