2010-04-21 12 views
25

Bir UILabel çok fazla metin içeriyorsa, etiketlerimi yazı tipi boyutlarını küçülterek nasıl ayarlayabilirim?Bir UILabel küçültülmüş yazı tipi boyutunda metin yazabilirim

 descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(200, 30, 130, 150)]; 
    [descriptionLabel setFont:[Utils getSystemFontWithSize:14]]; 
    [descriptionLabel setBackgroundColor:[UIColor clearColor]]; 
    [descriptionLabel setTextColor:[UIColor whiteColor]]; 
    descriptionLabel.numberOfLines = 1; 
    [self addSubview:descriptionLabel]; 

cevap

58
descriptionLabel.adjustsFontSizeToFitWidth = YES; 
descriptionLabel.minimumFontSize = 10.0; //adjust to preference obviously 

Aşağıdaki örnek test edilir ve iPhone Simülatörü 3.1.2 doğrulandı:

UILabel *descriptionLabel = [[UILabel alloc] initWithFrame:CGRectMake(90, 0, 200, 30)]; 

descriptionLabel.font = [UIFont systemFontOfSize:14.0]; 
descriptionLabel.minimumFontSize = 10.0; 
descriptionLabel.adjustsFontSizeToFitWidth = YES; 
descriptionLabel.numberOfLines = 1; 
descriptionLabel.text = @"supercalifragilisticexpialidocious even thought he sound of it is something quite attrocious"; 
+0

Bu satırı ekledim ama işe yaramıyor. Benim rectimi CGRectMake (200,30,10,10) gibi küçük bir şey olarak belirttiğimde bile hiçbir şey olmaz. –

+0

Tam olarak ne yaptığınızdan emin değilim [Utils getSystemFontWithSize:]:… cevabımı yeni test ettiğim ve doğruladığım bir örnek eklemek için düzenliyorum. – prendio2

+5

iOS 6'dan itibaren “minimumFontSize” yerine 'setMinimumScaleFactor' kullanılmalıdır. –

21

bir çok satırlı UILabel metni yeniden boyutlandırmak için, gelen code dayalı bu yardımcı yöntemini (kullanabilirsiniz 11 Piksel Studios):

+ (void)resizeFontForLabel:(UILabel*)aLabel maxSize:(int)maxSize minSize:(int)minSize { 
// use font from provided label so we don't lose color, style, etc 
UIFont *font = aLabel.font; 

// start with maxSize and keep reducing until it doesn't clip 
for(int i = maxSize; i >= minSize; i--) { 
    font = [font fontWithSize:i]; 
    CGSize constraintSize = CGSizeMake(aLabel.frame.size.width, MAXFLOAT); 

    // This step checks how tall the label would be with the desired font. 
    CGSize labelSize = [aLabel.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap]; 
    if(labelSize.height <= aLabel.frame.size.height) 
    break; 
} 
// Set the UILabel's font to the newly adjusted font. 
aLabel.font = font; 
} 
+0

For döngüsünüzde, koşul 'i> = minSize' olmalıdır,' i> 10' –

+0

değilsiniz .. teşekkürler @chrispix. –

0

sen hatlarının sayısı da gerekirse, bu nedenle eğer deyimi ile, Steve N'in çözümünü kullanmak artırmak istiyorsanız:

if(labelSize.height <= aLabel.frame.size.height) 
{ 
    aLabel.numberOfLines = labelSize.height/font.lineHeight; 

    break; 
} 
+3

Ya da sadece satır sayısını 0 olarak ayarlayın. – Jonathan

İlgili konular