2014-10-16 6 views
4

여러 개의 \n 개의 줄이 그 너비의 줄을 포함하도록 구성된 UILabel 일 수 있습니까> 잘리고 줄 바꿈되지 않을 레이블 너비? 나는 같은 일부 텍스트가줄 바꿈이없는 여러 줄의 UILabel?

가정하자 다음

  1. 이 수평
  2. 짧은 라인
  3. 또 다른 짧은 라인
에 맞게 너무 긴 텍스트의 정말로 긴 첫 번째 줄은

UILabel에 다음과 같이 표시하고 싶습니다.

 
1. This is a really long first line of text... 
2. Short line 
3. Another short line 

그러나 무슨 일이 일어나고 있는지 나는이납니다입니다 :

 
1. This is a really long first line of text 
that is too long to fit horizontally 
2. Short line... 

세 번째 줄이 끊어지고있다. 라인 수를 3으로 설정했지만, 여전히 첫 번째 긴 줄을 감싸고 있습니다. 레이블에 줄 바꿈 속성을 설정하는 것은 중요하지 않습니다. 항상 첫 줄을 래핑합니다. 라벨에 완전히 감쌀 수있는 방법이 있습니까?

답변

3

라벨에 적용 할 수있는 설정으로는 불가능하다고 생각합니다. 이를 수행하는 한 가지 방법은 문자열을 개별 줄로 분리하고 줄이 필요할 때마다 줄을 잘라서 한 줄에 맞도록 한 다음 줄 바꿈과 함께 줄을 다시 넣는 것입니다. 옵션 : 당신이 문자로 대신 말씀으로 절단하는 대신 enumerateSubstringsInRange의 옵션 매개 변수에 NSStringEnumerationByWords의 NSStringEnumerationByComposedCharacterSequences을 통과 할 수 원하는 경우이 같은 뭔가

@interface ViewController() 
@property (weak, nonatomic) IBOutlet UILabel *label; 
@property (nonatomic) CGFloat ellipsisWidth; 
@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    NSString *text = @"This is a really long first line of text that is too long to fit horizontally\nShort line\nAnother short line"; 
    NSString *ellipsis = @"..."; 
    self.ellipsisWidth = [ellipsis sizeWithAttributes:@{NSFontAttributeName:self.label.font}].width; 

    __block NSMutableString *truncatedString = [@"" mutableCopy]; 
    [text enumerateLinesUsingBlock:^(NSString *line, BOOL *stop) { 
     [truncatedString appendFormat:@"%@\n", [self oneLineOfString:line withFont:self.label.font]]; 
    }]; 
    NSString *finalString = [truncatedString stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]; 
    self.label.numberOfLines = 0; 
    self.label.text = finalString; 
} 

-(NSString *)oneLineOfString:(NSString *) aLine withFont:(UIFont *) font { 
    __block NSString *singleLine = nil; 
    __block NSString *lastFragment; 

    [aLine enumerateSubstringsInRange:NSMakeRange(0, aLine.length) options:NSStringEnumerationByWords usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { 
     NSString *textFragment = [aLine substringToIndex:(substringRange.location + substringRange.length)]; 
     CGRect textRect = [textFragment boundingRectWithSize:CGSizeMake(CGFLOAT_MAX ,CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil]; 
     if (textRect.size.width >= self.label.bounds.size.width - self.ellipsisWidth) { 
      singleLine = [lastFragment stringByAppendingString:@"..."]; 
      *stop = YES; 
     } 
     lastFragment = textFragment; 
    }]; 
    if (!singleLine) singleLine = aLine; // it doesn't need to be truncated, so return the passed in line 
    return singleLine; 
} 

, 라인의 수를 작동합니다 usingBlock을 :.

물론 쉽게 할 수 있습니다. 각 위에 3 개의 레이블을 쌓고 텍스트 한 줄을 둡니다.

+0

감사합니다. 힌트 또는 올바른 방향으로 포인터를 기대했지만,이 훌륭한 일하고있다! – devios1

관련 문제