2016-02-16 77 views
0

此圖片顯示了我想要實現:配件按鈕上的文字大小,以匹配按鈕大小

enter image description here

我指定的2個按鈕的寬度是相同的0.4 * redViewWidth和高度0.8 * redViewheight。比我想要的文字大小爲2行,儘可能大,仍然適合按鈕框架。我正在使用自定義字體並且沒有自動佈局。令我驚訝的是,這並沒有發生。該文本是在2行,但文字字體太大,並明確不適合按鈕大小。我哪裏做錯了?

編輯:redView使用自動佈局。用按鈕填充redView不使用。

let font = UIFont(name: "customfont", size: 19) 
    button1 = UIButton() 
    button2 = UIButton() 

    button1.frame = CGRectMake(navigationBarView.frame.width*0.6, navigationBarView.frame.height*0.1, navigationBarView.frame.width*0.4, navigationBarView.frame.height*0.8) 
    button2.frame = CGRectMake(navigationBarView.frame.width*0.2, navigationBarView.frame.height*0.1, navigationBarView.frame.width*0.4, navigationBarView.frame.height*0.8) 


    button1.setTitle("button2\ntext text text text", forState: UIControlState.Normal) 
    button1.titleLabel?.textAlignment = NSTextAlignment.Center 
    button1.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping 
    button1.titleLabel?.font=font 
    button1.titleLabel?.adjustsFontSizeToFitWidth=true 
    button1.titleLabel?.minimumScaleFactor = 0.1 
    button2.setTitle("button1\ntext text text text", forState: UIControlState.Normal) 
    button2.titleLabel?.textAlignment = NSTextAlignment.Center 
    button2.titleLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping 
    button2.titleLabel?.font=font 
    button2.titleLabel?.adjustsFontSizeToFitWidth=true 
    button2.titleLabel?.minimumScaleFactor = 0.1 

回答

0

你需要指定的UILabel行數如下:

button1.titleLabel?.numberOfLines = 2 
button2.titleLabel?.numberOfLines = 2 

編輯: 從Dynamically changing font size of UILabel 兩者顯然,自動調整大小的標籤的字體大小,當你有一個單行只能。下面的代碼會自動調整UILabel的大小,並且應該足夠簡單,以便爲UIButton進行編輯(但是,這在Objective-C中)。

與iOS7開始,sizeWithFont變得過時。多行的情況下減少到:

factLabel.numberOfLines = 0; 
factLabel.lineBreakMode = NSLineBreakByWordWrapping; 
CGSize maximumLabelSize = CGSizeMake(factLabel.frame.size.width, CGFLOAT_MAX); 
CGSize expectSize = [factLabel sizeThatFits:maximumLabelSize]; 
factLabel.frame = CGRectMake(factLabel.frame.origin.x, factLabel.frame.origin.y, expectSize.width, expectSize.height); 
+0

其實,標題標籤在2行中已經有了這個意思。問題是文本字體大小不調整以匹配按鈕的框架。 – brumbrum

+0

看看編輯,另一種方法是遍歷字體大小,並檢查每個字體的lineHeight屬性,雖然這看起來有點怪異。 –

+0

感謝您的阻止。請原諒我,如果我誤解了代碼..我認爲這會改變按鈕框架,以適應其標題中的任何文本。在我的情況下,框架是固定的 - 總是0.4 * redViewWidth。這是需要改變以考慮iOS設備的不同屏幕的字體大小。 – brumbrum

0

我結束了這樣的事情。它會檢查屏幕寬度並相應地分配字體大小。硬編碼,但它訣竅。

let screenRect = UIScreen.mainScreen().bounds 
     let screenWidth = screenRect.size.width; 

var fontSize = 15 
     if screenWidth>410{ 
      fontSize = 19 
     }else if screenWidth>370{ 
      fontSize = 17 
     }else{ 
      fontSize = 15 

     } 
     let font = UIFont(name: "customfont", size: CGFloat(fontSize))