自动更改字体大小以适应快捷键

我已经尝试过,但没有成功,文本超出了button边界。

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

当我尝试以下时,所有的文字都适合,但文字保持小字体:

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

我怎样才能让字体自动适合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文件的答案的代码

你可以试试这个:

1.根据您的button的当前字体大小定义标题大小

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

2.检查您的标题是否符合button标题标签:

 if titleSize.width > button.titleLabel?.bounds.width{ //set the appropriate font size }else{ //set the appropriate font size or do nothing } 

这对我工作:

  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 

UIButton字体缩放可能会变得非常浮躁,过去我遇到过问题。 我所做的是使行数等于1,这对我有效。