adjustsFontSizeToFitWidth使文本太小/试图检查字体大小

时间:2015-11-18 18:43:14

标签: ios swift text fonts font-size

我在我的代码中创建了多个按钮,每个按钮都从不同的数组中抓取它的文本。我使用adjustsFontSizeToFitWidth = true(这是我能找到的唯一可以自动调整文本大小的内容,因此它适合按钮的框架)。但是,当一些文本调整时,它可能会变得非常小;它肯定比它需要的要小。有什么方法可以确保文本只根据需要调整大小吗?

override func viewDidLoad() {
    super.viewDidLoad()

    correctWord.text = correctAnswer[questionNumber]

    correctWord.frame = CGRectMake(0, 0, 1 * self.view.frame.width / 4, 1.5 * self.view.frame.height / 22)

    correctWord.center = CGPointMake(self.view.bounds.width / 2, 14.25 * self.view.bounds.height / 22)

    correctWord.textAlignment = NSTextAlignment.Center

    correctWord.numberOfLines = 1

    correctWord.font = UIFont(name: "Chalkboard SE", size: 60)

    correctWord.textColor = UIColor.greenColor()

    correctWord.adjustsFontSizeToFitWidth = true

    correctWord.baselineAdjustment = .AlignCenters

    correctWord.minimumScaleFactor = 0.1

    self.view.addSubview(correctWord)

我尝试搜索时看到的代码(见下文)。我为代码创建了一个函数来更新文本大小,我在self.view.addSubview(correctWord)之前调用它。但是,按钮永远不会出现。而且,有没有办法可以检查字体大小究竟是什么?当我将currentSize打印到日志以确定字体大小时,它总是显示“0”。我试图确定哪个文本的大小最小,因此所有按钮都可以设置为相同的字体大小。

func adjustFontSizeToFitRect(rect : CGRect){

    if correctWord.text == nil{
        return
    }

    correctWord.frame = rect

    let maxFontSize: CGFloat = 100.0
    let minFontSize: CGFloat = 5.0

    var q = Int(maxFontSize)
    var p = Int(minFontSize)

    let constraintSize = CGSize(width: rect.width, height: CGFloat.max)

    while(p <= q){
         currentSize = (p + q) / 2

        correctWord.font = UIFont(name: "Chalkboard SE", size: CGFloat(currentSize))

        let textRect = correctWord.text!.boundingRectWithSize(constraintSize, options: .UsesLineFragmentOrigin, attributes: nil, context: nil)


        let labelSize = textRect.size

        if labelSize.height < correctWord.frame.height && labelSize.height >= correctWord.frame.height-10 && labelSize.width < correctWord.frame.width && labelSize.width >= correctWord.frame.width-10 {
            break
        }else if labelSize.height > correctWord.frame.height || labelSize.width > correctWord.frame.width{
            q = currentSize - 1
        }else{
            p = currentSize + 1
        }
    }

}

0 个答案:

没有答案
相关问题