自动更改字体大小以适应swift中的按钮 [英] Auto change the font size to fit the button in swift
本文介绍了自动更改字体大小以适应swift中的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试过这个,但它不起作用,文字超出按钮边界。
I have tried this but it didn't work, the text is out of the button boundaries.
button.titleLabel!.adjustsFontSizeToFitWidth = true
button.titleLabel!.numberOfLines = 0
button.titleLabel!.minimumScaleFactor = 0.1
当我尝试以下操作时,所有文字都适合,但文字保持小字体:
When I try the following, all the text fits, but the text remains in a small font:
button.titleLabel!.font = UIFont(name: "Heiti TC", size: 9)
如何让字体自动适应按钮的大小?
How can I get the font to automatically fit the size of the button?
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文件中得到答案的代码
That is the code I have so far it gets the answers from a plist file
推荐答案
你可以试试这个:
1.根据按钮的当前字体大小定义标题大小
1.define the title size based on the current font size of your button
let nsTitle = NSString(string:"yourButtonTitle")
let font = button.titleLabel?.font
let titleSize = nsTitle.sizeWithAttributes([NSFontAttributeName:font])
2.检查您的标题是否适合按钮标题标签:
2.check whether your title fits the button title label :
if titleSize.width > button.titleLabel?.bounds.width{
//set the appropriate font size
}else{
//set the appropriate font size or do nothing
}
这篇关于自动更改字体大小以适应swift中的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文