【问题标题】:Set matching font sizes on UILabels in a UITableViewCell when one Label adjustFontSizeToFitWidth当一个标签 adjustFontSizeToFitWidth 时,在 UITableViewCell 中的 UILabel 上设置匹配的字体大小
【发布时间】:2018-07-02 02:50:28
【问题描述】:

我在自定义tableViewCell 中有两个UILabel。一个标签具有宽度限制,并在较小的屏幕上设置为 adjustFontSizeToFitWidth,例如5S。当它没有特定的宽度限制时,如何让另一个 UILabel 匹配第一个标签的字体大小?

似乎 sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode: 在 iOS7 中已被弃用,那么 Swift 解决方案是什么?

这个答案When do adjustsFontSizeToFitWidth or boundingRectWithSize change the context.actualScaleFactor? 不完整,我需要在 TableViewCell 中进行。

这就是我的自定义表格视图单元格类中的内容。但它只是拾取原始尺寸而不是调整后的尺寸。

class CustomTVC: UITableViewCell {

@IBOutlet weak var rowTitle: UILabel!
@IBOutlet weak var rowSubtitle: UILabel!

override func awakeFromNib() {
    super.awakeFromNib()
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // makes the rowSubtitle and title have matching fonts in case of 5S
    let attributes = [NSAttributedStringKey.font: rowTitle.font]
    let textString = rowTitle.text
    let attributedString = NSMutableAttributedString(string:textString!, attributes:attributes)

    let context = NSStringDrawingContext()
    context.minimumScaleFactor = rowTitle.minimumScaleFactor
    let resultingRect = attributedString.boundingRect(with: rowTitle.bounds.size, options: .usesLineFragmentOrigin, context:context)

    print("actual context after drawing: \(context.actualScaleFactor)")

    let actualFontSize = rowTitle.font.pointSize * context.actualScaleFactor
    print("actual font size is: \(actualFontSize)")
}
}

【问题讨论】:

    标签: ios swift uitableview uilabel


    【解决方案1】:

    这是我能想到的所有解决方法。希望有人会发布一个更好的方法来实际使用 adjustSizeToFitWidth。

    let ScreenWidth = UIScreen.main.bounds.size.width
        var font = UIFont()
        if ScreenWidth < 321 {
            font = UIFont.systemFont(ofSize: 16, weight: .light)
        } else {
            font = UIFont.systemFont(ofSize: 19, weight: .light)
        }
        rowTitle.font = font
        rowSubtitle.font = font
    

    【讨论】:

      猜你喜欢
      • 2019-01-15
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 2011-01-24
      • 1970-01-01
      • 1970-01-01
      • 2018-03-30
      相关资源
      最近更新 更多