2015-08-08 42 views
1

這裏是我的UILabel(由什麼是黃色的定義): enter image description here如何在不改變字體大小的情況下修剪UILabel的高度以完美地適應文字?

下面是我後添加[shortDescriptionLabel sizeToFit]結束的我的代碼: enter image description here

這是第二個實施例(以顯示字體大小實際上得到sizeToFit之後改變: enter image description here

下面是我添加後[shortDescriptionLabel sizeToFit];結束我的代碼(很顯然,字體大小恢復到尺寸30.0):

enter image description here

我想修剪多餘的高度(高於或低於胡蘿蔔),我該怎麼辦次是什麼?這裏是我當前的代碼:

shortDescriptionLabel = [[UILabel alloc]initWithFrame:CGRectMake(itemImageView.frame.origin.x+itemImageView.frame.size.width+10, 20, self.tableView.frame.size.width-itemImageView.frame.origin.x- itemImageView.frame.size.width-20-20, tableViewCellHeight/2)]; 
    shortDescriptionLabel.text = itemObject.shortDescription; 
    shortDescriptionLabel.font = [UIFont boldSystemFontOfSize:30]; 
    shortDescriptionLabel.textAlignment = NSTextAlignmentCenter; 
    shortDescriptionLabel.adjustsFontSizeToFitWidth = YES; 
    shortDescriptionLabel.numberOfLines = 0; 
    shortDescriptionLabel.minimumScaleFactor = 0; 
    [shortDescriptionLabel setBackgroundColor:[UIColor yellowColor]]; 
    CGFloat fontSize = shortDescriptionLabel.font.pointSize; 
    NSLog(@"fontSize = %f", fontSize); 

請記住,最後的NSLog將始終顯示30.0(字體大小先前設置),即使顯示的字體大小明顯大於30.0較小。

請幫忙。網上似乎有很多,但我似乎無法得到任何工作。

+2

當你在調用'sizeToFit'嗎? – rmaddy

+0

我嘗試在所有內容的末尾添加行。 –

+0

調用'sizeToFit'後顯示標籤的外觀。確保文本沒有換行符或其他空格。 – rmaddy

回答

0

Yoh可以使用sizeToFit但是如果你想修剪高度並保持寬度,你可以添加一個高度約束等於使用的UIFont的lineHeight

0

自動版式

1 - 適當加其前置,頂部和底部約束和寫這行代碼會做

[label setPreferredMaxLayoutWidth:300.0]; 

非自動版式

-(CGSize)m_GetHeight:(NSString*)text 
{ 
    CGSize constraintSize=[text sizeWithFont:[UIFont fontWithName:@"Arial" size:15.] constrainedToSize:CGSizeMake(182, 2000) lineBreakMode:NSLineBreakByWordWrapping]; 
    return constraintSize; 

} 
+0

我不確定設置最大寬度的設置。我擔心身高:S –

+0

當您指定最大寬度時,它會根據其內容大小自動調整其高度。 –

+0

問題不在於我的寬度。正如你在例子中看到的那樣,寬度永遠不會超過它不應該在的地方。 –

相關問題