我有一个正方形~/Frames/ReportLauncher.aspx?ID=Inquirycase.rpx&CASEID=####
(黄色),其中包含一个字母。
我使用了this SO answer中的以下代码来调整字体大小,使其适合UILabel
:
UILabel
如截图所示,字体大小取决于宽度。但由于文字只有一个字母,因此我们还需要查看高度。我们如何调整字体大小,使得高度也在letterLabel.font = UIFont(name: letterLabel.font.fontName, size: 100)
letterLabel.adjustsFontSizeToFitWidth = true
letterLabel.textAlignment = NSTextAlignment.Center
?
答案 0 :(得分:0)
我没有找到任何简单的解决方案,所以我做了这个扩展:
extension UILabel {
func setFontSizeToFill() {
let frameSize = self.bounds.size
guard frameSize.height>0 && frameSize.width>0 && self.text != nil else {return}
var fontPoints = self.font.pointSize
var fontSize = self.text!.size(withAttributes: [NSAttributedStringKey.font: self.font.withSize(fontPoints)])
var increment = CGFloat(0)
if fontSize.width > frameSize.width || fontSize.height > frameSize.height {
increment = -1
} else {
increment = 1
}
while true {
fontSize = self.text!.size(withAttributes: [NSAttributedStringKey.font: self.font.withSize(fontPoints+increment)])
if increment < 0 {
if fontSize.width < frameSize.width && fontSize.height < frameSize.height {
fontPoints += increment
break
}
} else {
if fontSize.width > frameSize.width || fontSize.height > frameSize.height {
break
}
}
fontPoints += increment
}
self.font = self.font.withSize(fontPoints)
}
}
答案 1 :(得分:0)
我只需要在标签上显示一个字母(名字开头),所以要求很明确,它必须缩放以适合高度。
解决方案:
class AnyView : UIView{
private var nameLabel:UILabel! = nil
override func layoutSubviews() {
super.layoutSubviews()
//Considering the nameLabel has been already created and added as subview with all the constraint set
nameLabel.font = nameLabel.font.withSize(nameLabel.bounds.height * 0.6/*The factor can be adjusted as per need*/)
}
}
答案 2 :(得分:0)
答案 3 :(得分:-3)
尝试[label sizeToFit]
或[label sizeThatFits:(CGSize)]