我在自定义 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/