我有一个UILabel,字体大小为17.如果我调用label.font.pointSize,我会得到17,这一切都很好。 BBUUUUTTT我也有一个最小字体大小设置为8,现在如果我在标签中塞入一些文本导致点大小缩小然后调用label.font.pointsize我仍然得到17即使我知道点大小较小
如何在系统调整字体大小后获得真正的磅值?
答案 0 :(得分:4)
我不知道在缩放内容时获取UILabel的当前磅值的API。您可以尝试使用sizeWithFont
API来近似“缩放因子”。
只是一个想法:
// Get the size of the text with no scaling (one line)
CGSize sizeOneLine = [label.text sizeWithFont:label.font];
// Get the size of the text enforcing the scaling based on label width
CGSize sizeOneLineConstrained = [label.text sizeWithFont:label.font constrainedToSize:label.frame.size];
// Approximate scaling factor
CGFloat approxScaleFactor = sizeOneLineConstrained.width / sizeOneLine.width;
// Approximate new point size
CGFloat approxScaledPointSize = approxScaleFactor * label.font.pointSize;
答案 1 :(得分:2)
正如savner在评论中指出的那样,这是一个重复的问题。最清晰的解决方案可以在这里找到:How to get UILabel (UITextView) auto adjusted font size?。但是,Sanjit的解决方案也有效!谢谢大家!
CGFloat actualFontSize;
[label.text sizeWithFont:label.font
minFontSize:label.minimumFontSize
actualFontSize:&actualFontSize
forWidth:label.bounds.size.width
lineBreakMode:label.lineBreakMode];
答案 2 :(得分:0)
Swift 4 和 iOS 7 + 版本(sizeWithFont
现已弃用):
// Get the size of the text with no scaling (one line)
let sizeOneLine: CGSize = label.text!.size(withAttributes: [NSAttributedStringKey.font: label.font])
// Get the size of the text enforcing the scaling based on label width
let sizeOneLineConstrained: CGSize = label.text!.boundingRect(with: label.frame.size, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: label.font], context: nil).size
// Approximate scaling factor
let approxScaleFactor: CGFloat = sizeOneLineConstrained.width / sizeOneLine.width
// Approximate new point size
let approxScaledPointSize: CGFloat = approxScaleFactor * label.font.pointSize