我通过扩展UITextView来实现自定义的富文本编辑器.当用户选择文本范围并使用"突出显示"菜单时,编辑器将为所选文本绘制蓝色背景:
- (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 - …Run Code Online (Sandbox Code Playgroud)