2017-04-24 46 views
1

我有一個UILabel這需要在某些情況下以及雲在UILabel不一定適合方形UILabel及正是由於這個原因,我需要計算量的文本廣場文本將適合UILabel的框架。我用這一段代碼來獲得字符串的索引,子到會融入的UILabel -計算子

CGFloat labelWidth  = self.textLabel.frame.size.width; 
CGFloat labelHeight = self.textLabel.frame.size.height - titleRect.size.height - 16.0; 
CGSize sizeConstraint = CGSizeMake(labelWidth, CGFLOAT_MAX); 

NSDictionary *attributes = @{ NSFontAttributeName : font}; 

CGRect boundingRect = [body boundingRectWithSize:sizeConstraint options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:attributes context:nil]; 
if (boundingRect.size.height > labelHeight) 
{ 
    NSUInteger stringIndex = 0; 
    NSUInteger prev; 
    NSCharacterSet *characterSet = [NSCharacterSet whitespaceAndNewlineCharacterSet]; 
    do 
    { 
     prev = stringIndex; 
     if (mode == NSLineBreakByCharWrapping) 
      stringIndex++; 
     else 
      stringIndex = [body rangeOfCharacterFromSet:characterSet options:0 range:NSMakeRange(stringIndex + 1, [body length] - stringIndex - 1)].location; 
    } 

    while (stringIndex != NSNotFound && stringIndex < [body length] && [[body substringToIndex:stringIndex] boundingRectWithSize:sizeConstraint options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:attributes context:nil].size.height <= labelHeight); 

    return prev; 
} 

我開始使用這個指數的子串過於大,超出框架UILabel

我做錯了什麼?

編輯

我試圖使用NSLineBreakByTruncatingTail由@rmaddy的建議,但UILabel這是一個UIScrollView內拒絕堅持它的框架。下面是代碼 -

self.textLabel.lineBreakMode = NSLineBreakByTruncatingTail; 
self.textLabel.frame = CGRectMake(self.textLabel.frame.origin.x, self.textLabel.frame.origin.y, self.textLabel.frame.size.width, self.textLabel.frame.size.width); 
[self setText:self.titleText andBody:self.bodyText andFontName:fontname andSize:size andColor:self.color]; 

我想設置在UILabel文本使它調整其高度。我已經嘗試在設置框架之前設置文本,但它也不起作用。現在我一直陷在這裏太久了。

+2

爲什麼去的麻煩。只需將標籤的「lineBreakMode」設置爲「NSLineBreakByTruncatingTail」即可。 – rmaddy

+0

@rmaddy從未到過我的腦海。讓我試試看看是否符合我的要求 – genaks

+0

@rmaddy如果記錄textLabel的文本,我會得到什麼?整個字符串或截斷的字符串?我問這是因爲我還需要截斷的字符串。 – genaks

回答

0

您可以做的是檢查字符串的長度並將其調整爲標籤寬度。

事情是這樣的:

CGSize sizeOfText = [self.label.text boundingRectWithSize: CGSizeMake(self.label.intrinsicContentSize.width, CGFLOAT_MAX) 
              options: (NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) 
              attributes: [NSDictionary dictionaryWithObject:self.label.font forKey:NSFontAttributeName] context: nil].size; 

if (self.label.intrinsicContentSize.height < ceilf(sizeOfText.height)) { 
// label is truncated 
// so do something here 
}else{ 
// in here do something else 
}