ios – 自动更改字体大小以适应swift中的按钮

前端之家收集整理的这篇文章主要介绍了ios – 自动更改字体大小以适应swift中的按钮前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试过这个,但它不起作用,文本超出按钮边界.
  1. button.titleLabel!.adjustsFontSizeToFitWidth = true
  2. button.titleLabel!.numberOfLines = 0
  3. button.titleLabel!.minimumScaleFactor = 0.1

当我尝试以下操作时,所有文本都适合,但文本仍然是小字体:

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

如何让字体自动适合按钮的大小?

  1. func nextQuestion() {
  2.  
  3. let currentQuestion = mcArray![questionIdx]
  4.  
  5. answers = currentQuestion["Answers"] as! [String]
  6. correctAnswer = currentQuestion["CorrectAnswer"] as? String
  7. question = currentQuestion["Question"] as? String
  8.  
  9. titlesForButtons()
  10. }
  11.  
  12. func titlesForButtons() {
  13. for (idx,button) in answerButtons.enumerate() {
  14. button.titleLabel!.lineBreakMode = .ByWordWrapping
  15.  
  16. button.titleLabel!.font = UIFont(name: "Heiti TC",size: 5)
  17.  
  18. button.titleLabel!.numberOfLines = 0
  19.  
  20. button.titleLabel!.minimumScaleFactor = 0.1
  21.  
  22. button.titleLabel!.baselineAdjustment = .AlignCenters
  23.  
  24. button.titleLabel!.textAlignment = NSTextAlignment.Center
  25.  
  26. button.setTitle(answers[idx],forState: .Normal)
  27. button.enabled = true
  28. button.backgroundColor = UIColor(red: 83.0/255.0,green: 184.0/255.0,blue: 224.0/255.0,alpha: 1.0)
  29. }
  30.  
  31. questionLabel.text = question
  32. startTimer()
  33. }

这是我到目前为止的代码,它从plist文件获取答案

解决方法

你可以试试这个:

1.根据按钮的当前字体大小定义标题大小

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

2.检查您的标题是否适合按钮标题标签

  1. if titleSize.width > button.titleLabel?.bounds.width{
  2.  
  3. //set the appropriate font size
  4.  
  5. }else{
  6.  
  7. //set the appropriate font size or do nothing
  8. }

猜你在找的iOS相关文章