简体   繁体   中英

Different texts in UILabel remain the same font size in UICollectionView Cells

For instance,

  1. I have 4 itemsInSection from UICollectionView, they have same height and width based on device size.
  2. For the UILabel inside of cell, make it equal width and height with multiplier 1:3 of cell. I want UILabel size grow or shrink when screen size changed.
  3. Texts in UILabel for each cell are different, such as "Pen", "Documents", "Lee" and "Beats"
  4. I set fontSize = 22pt, minimumScaleFactor is 0.5 and adjustsFontSizeToFitWidth is true
  5. But the problem is "Documents" will be the smallest font size, all other text font looks much bigger than it.

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.

iPhone SE屏幕快照

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM