ios - 当一个 Label adjustFontSizeToFitWidth 时,在 UITableViewCell 的 UILabels 上设置匹配的字体大小

标签 ios swift uitableview uilabel

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

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

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

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

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)")
}
}

最佳答案

这是我能想到的所有解决方法。希望有人会发布更好的方法来实际使用 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

关于ios - 当一个 Label adjustFontSizeToFitWidth 时,在 UITableViewCell 的 UILabels 上设置匹配的字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48399102/

相关文章:

ios - 在 iOS 上自动获取用户所在国家/地区的最准确方法?

ios - 如何从字典数组中获取数据 - swift

ios - 节和行未正确显示在UITableView Swift中

ios - Quickblox - 获取用户 friend 的头像并显示在 UITableView 中

iphone - 使用 ASIHTTPRequest 的 UITableViewCell 中的 UIImageView 性能

iOS Firebase/Firestore 权限被拒绝

ios - 如何使用 Cocos2d、SpriteBuilder 和 Objective-c 创建弹窗?

ios - UIAlertController 作为跨 View Controller 访问的通用函数

ios - TableView Cell 找不到成员 NSNumber 变量

objective-c - NSFetchedResultsController、sectionNameKeyPath 和没有数据的日期部分