【问题标题】:Auto change the font size to fit the button in swift自动更改字体大小以快速适应按钮
【发布时间】:2016-10-29 22:44:32
【问题描述】:

我试过了,但没用,文本超出了按钮边界。

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 文件中获取答案的代码

【问题讨论】:

  • adjustsFontSizeToFitWidth = true 为我工作。
  • 它不起作用,文本大小相同,超出了按钮边界

标签: ios swift uibutton uifont


【解决方案1】:

你可以试试这个:

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
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      这对我有用:

       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
      

      【讨论】:

        【解决方案4】:

        调整字体大小以适应宽度

        斯威夫特

        self.button.titleLabel?.adjustsFontSizeToFitWidth = true
        

        Objective-C

        [self.button.titleLabel setAdjustsFontSizeToFitWidth:YES];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-11-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多