Swift - 调整fontSize以适应布局的宽度(以编程方式)

MLy*_*yck 32 xcode fonts ios swift

我一直在寻找动态调整我的东西以fontSize适应我的布局框的宽度.但我能找到的所有答案都是要么:

label.adjustsFontSizeToFitWidth = true
Run Code Online (Sandbox Code Playgroud)

哪个确实有效.但是,只有我没有setTranslatesAutoresizingMaskIntoConstraints设置false.

请注意,我不使用故事板.因此,为了完全控制我的其他约束,我需要这一行:

label.setTranslatesAutoresizingMaskIntoConstraints(false)
Run Code Online (Sandbox Code Playgroud)

那么如何在不使用故事板的情况下调整字体大小以适应宽度,何时无法使用adjustsFontSizeToFitWidth.

在我弄清楚如何调整字体大小以适应宽度之后.我还需要调整布局框的高度以适应字体大小.虽然似乎有关于这方面的文件,但如果你碰巧知道这个问题的答案,我将不胜感激.

提前致谢

Roi*_*lia 45

请为您的标签尝试以下命令:

label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.2
Run Code Online (Sandbox Code Playgroud)

并尝试将标签的行更改为0和1(检查两种情况):

label.numberOfLines = 0 // or 1
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是我不能使用"label.adjustsFontSizeToFitWidth = true",因为我使用程序化约束,因此我需要以下行label.setTranslatesAutoresizingMaskIntoConstraints(false),这似乎打破了adjustFontSizeToFitWith.不幸的是,我尝试了两种方案.感谢您的回复!我很感激. (2认同)

Vin*_*ose 15

MinimumScaleFactor范围是0到1.因此我们按照以下方式设置MinimumScaleFactor字体大小

目标C.

[lb setMinimumScaleFactor:10.0/[UIFont labelFontSize]]; lb.adjustsFontSizeToFitWidth = YES;

Swift 3.0

lb.minimumScaleFactor = 10/UIFont.labelFontSize lb.adjustsFontSizeToFitWidth = true


Sea*_*159 7

我不知道这是否能完全回答你的问题,但你可以使用这个扩展来计算你自己的字体大小。

斯威夫特 3

extension String {
   func height(constrainedBy width: CGFloat, with font: UIFont) -> CGFloat {
       let constraintSize = CGSize(width: width, height: .max)
       let boundingBox = self.boundingRectWithSize(constraintSize, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

       return boundingBox.height
   }

   func width(constrainedBy height: CGFloat, with font: UIFont) -> CGFloat {
       let constrainedSize = CGSize(width: .max, height: height)
       let boundingBox = self.boundingRectWithSize(constrainedSize, options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

       return boundingBox.width
   }
}
Run Code Online (Sandbox Code Playgroud)

更新 - 向 Swift 5 添加示例和更新代码

斯威夫特 5

extension String {
    func height(constrainedBy width: CGFloat, with font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)

        return boundingBox.height
    }

    func width(constrainedBy height: CGFloat, with font: UIFont) -> CGFloat {
        let constrainedRect = CGSize(width: .greatestFiniteMagnitude, height: height)
        let boundingBox = self.boundingRect(with: constrainedRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)

        return boundingBox.width
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我确保两个不同标签具有相同字体大小的逻辑。就我而言,它是用户名字和姓氏的两个标签。我为此需要两个标签的原因是每个标签都是独立动画的。

class ViewController: UIViewController {
      ...

      func viewDidLoad() {
         super.viewDidLoad()
         fixFontSizes()
         ...
      }

      func fixFontSizes() {
         let leadingMargin = self.leadingContainerConstraint.constant
         let trailingMargin = self.trailingContainerConstraint.constant
         let maxLabelWidth = self.view.bounds.width - leadingMargin - trailingMargin

         let firstName = self.firstNameLabel.text ?? ""
         let lastName = self.lastNameLabel.text ?? ""

         let firstNameWidth = firstName.width(constrainedBy: self.container.bounds.height, with: self.firstNameLabel.font)
         let lastNameWidth = lastName.width(constrainedBy: self.container.bounds.height, with: self.lastNameLabel.font)

         let largestLabelWidth = max(firstNameWidth, lastNameWidth)
         guard largestLabelWidth > maxLabelWidth else { return }

         let largestTextSize = max(self.firstNameLabel.font.pointSize, self.lastNameLabel.font.pointSize)

         let labelToScreenWidthRatio = largestLabelWidth / maxLabelWidth
         let calculatedMaxTextSize = floor(largestTextSize / labelToScreenWidthRatio)

         self.firstNameLabel.font = self.firstNameLabel.font.withSize(calculatedMaxTextSize)
         self.lastNameLabel.font = self.lastNameLabel.font.withSize(calculatedMaxTextSize)
      }


}
Run Code Online (Sandbox Code Playgroud)


Roi*_*lia 6

我只是做了你需要的,效果完美!(仅以编程方式) - 我们正在为标签设置大字体大小,以便将其重新缩放到完美的字体大小。

self.label.font = UIFont(name: "Heiti TC", size: 60)
self.label.numberOfLines = 0
self.label.minimumScaleFactor = 0.1
self.label.baselineAdjustment = .alignCenters
self.label.textAlignment  = .center
Run Code Online (Sandbox Code Playgroud)

如果您使用自动布局,请在viewDidLayoutSubviews(布局布局后)实现此代码。

你的,罗伊