简体   繁体   English

UILabel中的不同文本在UICollectionView单元格中保持相同的字体大小

[英]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. 我有4个来自UICollectionView的itemInSection,它们根据设备大小具有相同的高度和宽度。
  2. For the UILabel inside of cell, make it equal width and height with multiplier 1:3 of cell. 对于单元格内部的UILabel,将其乘以单元格的1:3使其宽度和高度相等。 I want UILabel size grow or shrink when screen size changed. 我希望UILabel大小在屏幕大小更改时增加或缩小。
  3. Texts in UILabel for each cell are different, such as "Pen", "Documents", "Lee" and "Beats" UILabel中每个单元格的文本都是不同的,例如“笔”,“文档”,“李”和“节拍”
  4. I set fontSize = 22pt, minimumScaleFactor is 0.5 and adjustsFontSizeToFitWidth is true 我设置fontSize = 22pt,minimumScaleFactor为0.5并将adjustsFontSizeToFitWidth为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? 问题 :如何使所有UILabel文本大小与最长文本相同,并且同时使字体大小根据屏幕大小缩小或增大?

Eg. 例如。 iPhone 8 Plus font size should be bigger than iPhone SE font size, because we have more room on iPhone 8 Plus. iPhone 8 Plus字体大小应大于iPhone SE字体大小,因为我们在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. 将其他标签的字体大小固定到最长标签的字体大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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