2016-06-27 45 views
8

到合適的按鈕我都試過,但沒有奏效,文字離開按鈕的邊界。自動更改字體大小在迅速

button.titleLabel!.adjustsFontSizeToFitWidth = true 
button.titleLabel!.numberOfLines = 0 
button.titleLabel!.minimumScaleFactor = 0.1 

當我嘗試以下方法,所有的文本適合,但文本保持在一個小字體:

button.titleLabel!.font = UIFont(name: "Heiti TC", size: 9) 

我怎樣才能獲得字體自動適應按鈕的尺寸?

func nextQuestion() { 

    let currentQuestion = mcArray![questionIdx] 

    answers = currentQuestion["Answers"] as! [String] 
    correctAnswer = currentQuestion["CorrectAnswer"] as? String 
    question = currentQuestion["Question"] as? String 

    titlesForButtons() 
} 

func titlesForButtons() { 
    for (idx,button) in answerButtons.enumerate() { 
     button.titleLabel!.lineBreakMode = .ByWordWrapping 

     button.titleLabel!.font = UIFont(name: "Heiti TC", size: 5) 

     button.titleLabel!.numberOfLines = 0 

     button.titleLabel!.minimumScaleFactor = 0.1 

     button.titleLabel!.baselineAdjustment = .AlignCenters 

     button.titleLabel!.textAlignment = NSTextAlignment.Center 

     button.setTitle(answers[idx], forState: .Normal) 
     button.enabled = true 
     button.backgroundColor = UIColor(red: 83.0/255.0, green: 184.0/255.0, blue: 224.0/255.0, alpha: 1.0) 
    } 

    questionLabel.text = question 
    startTimer() 
} 

這是我迄今它從一個plist文件的答案

+0

'adjustsFontSizeToFitWidth = TRUE'爲我工作。 – keithbhunter

+0

它沒有工作文本是相同的大小,並走出了按鈕界限 – acekidd

回答

4

你可以試試這個代碼:

1.定義基於當前字體大小標題的大小按鈕

let nsTitle = NSString(string:"yourButtonTitle") 
let font = button.titleLabel?.font 
let titleSize = nsTitle.sizeWithAttributes([NSFontAttributeName:font]) 

2.檢查您的標題是否符合按鈕標題標籤:

if titleSize.width > button.titleLabel?.bounds.width{ 

    //set the appropriate font size 

}else{ 

    //set the appropriate font size or do nothing 
} 
0

UIButton的字體縮放可以是非常善變的,我已經在過去與它的問題。我所做的就是讓行數等於1,這對我來說很合適。

2

這爲我工作:

button.titleLabel!.font = UIFont(name: "Avenir Next", size: 20) 
    button.titleLabel!.adjustsFontSizeToFitWidth = true 
    button.titleLabel!.numberOfLines = 1 
    button.titleLabel!.minimumScaleFactor = 0.1 
    button.clipsToBounds = true 
+1

謝謝,它完全爲我工作! ;-) –