2013-02-26 3 views
1

UITextView를 확장하여 사용자 정의 된 서식있는 텍스트 편집기를 구현하고 있습니다. 선택한 텍스트를 줄 바꿈의 원인이 긴 단어가 포함 된 경우, 파란색 배경을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 - 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); 
    } 
} 

: 사용자가 텍스트 범위와 사과 '강조'메뉴를 선택하면, 편집기는 선택된 텍스트 파란색 배경을 그릴 것입니다 못 생겼어.

enter image description here

단어 줄 바꿈 위치를 감지 할 수있는 방법이 있습니까? 감사!

답변

7

좋아, 결국이 문제를 해결했습니다. 단어 랩 또는 새 줄 바꿈을 검출하기 위해, 그것은 다음 코드를 사용하기 간단합니다 iOS7에 모든 :

+0

이 휴식의

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

합니다. 보상 방법을 모릅니다. ContentSize.height는 더 이상 무언가의 높이를 찾는 신뢰할만한 방법이 아닙니다. –

관련 문제