2013-10-24 65 views
2

我有一個改變文本的按鈕。減少第三行的UIButton標籤字體大小

我想要如果按鈕文本去第三行它應該減少其字體minimumScaleFactor。我使用此代碼

self.option1Button.titleLabel.minimumScaleFactor = .7; 
self.option1Button.titleLabel.numberOfLines = 2; 
self.option1Button.titleLabel.adjustsFontSizeToFitWidth = TRUE; 

但是,這是行不通的。當文本到達第三行時它不會更改字體大小。

回答

4

adjustToFit只適用於單行標籤。

嘗試做this

//Create a string with the text we want to display. 
self.ourText = @"This is your variable-length string. Assign it any way you want!"; 

/* This is where we define the ideal font that the Label wants to use. 
Use the font you want to use and the largest font size you want to use. */ 
UIFont *font = [UIFont fontWithName:@"Marker Felt" size:28]; 

int i; 
/* Time to calculate the needed font size. 
This for loop starts at the largest font size, and decreases by two point sizes (i=i-2) 
Until it either hits a size that will fit or hits the minimum size we want to allow (i > 10) */ 
for(i = 28; i > 10; i=i-2) { 
    // Set the new font size. 
    font = [font fontWithSize:i]; 
    // You can log the size you're trying: NSLog(@"Trying size: %u", i); 

    /* This step is important: We make a constraint box 
    using only the fixed WIDTH of the UILabel. The height will 
    be checked later. */ 
    CGSize constraintSize = CGSizeMake(260.0f, MAXFLOAT); 

    // This step checks how tall the label would be with the desired font. 
    CGSize labelSize = [self.ourText sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap]; 

    /* Here is where you use the height requirement! 
    Set the value in the if statement to the height of your UILabel 
    If the label fits into your required height, it will break the loop 
    and use that font size. */ 
    if(labelSize.height <= 180.0f) 
     break; 
} 
// You can see what size the function is using by outputting: NSLog(@"Best size is: %u", i); 

// Set the UILabel's font to the newly adjusted font. 
msg.font = font; 

// Put the text into the UILabel outlet variable. 
msg.text = self.ourText; 
+0

由於某些原因,我在界面生成器中使用fontSize和height,所以這不適用於我。 –

+1

@AzkaarAli你必須在代碼中做一些。我想,你的需求在界面製作工具中是不能滿足的。此外,上面的'sizeWithFont'已被iOS 7中的新功能('boundingRectWithSize')所取代。 – Mundi

1

如果你想讓你的按鈕顯示三行,你必須將numberOfLines設置爲3.奇怪但是是真的。

+1

不,我只想要2行,如果文本超過2行,就應減少字體大小以適合在2行。 –