For instance,
Question : How can I make all UILabel text size same as the longest text one and same time the font size should shrink or grow based on screen size?
Eg. iPhone 8 Plus font size should be bigger than iPhone SE font size, because we have more room on iPhone 8 Plus.
You can check which label has the largest number of characters using:
label.text.count
once you know which is the longest, you can just use a simple extension like:
extension UILabel{
func anchorFontSize(toLabel: UILabel) {
let text: NSMutableAttributedString = NSMutableAttributedString(attributedString: toLabel.attributedText!)
text.setAttributes([NSAttributedStringKey.font: toLabel.font], range: NSMakeRange(0, text.length))
let context: NSStringDrawingContext = NSStringDrawingContext()
context.minimumScaleFactor = toLabel.minimumScaleFactor
text.boundingRect(with: toLabel.frame.size, options: NSStringDrawingOptions.usesLineFragmentOrigin, context: context)
let adjustedFontSize: CGFloat = toLabel.font.pointSize * context.actualScaleFactor
let font = self.font.fontName
self.font = UIFont(name: font, size: adjustedFontSize)
}
}
to anchor the font sizes of the other labels to the font size of the longest label.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.