首页 > 解决方案 > 如何在 CollectionViewCell 中动态调整 UITextView 字体大小?

问题描述

我有一个包含 UITextView 的 collectionView。我想动态设置 TextView 的字体大小。经过调查,我发现了以下代码。它适用于 UITextView 动态字体大小。如果文本很长,代码会根据 UITextView 的框架高度来安排最合适的字体大小。

但我的问题是,当 ViewController 确实加载时, UICollectionViewCell 中的 UITextView 字体大小没有正确更改。但是当我滑动到另一个单元格时,字体大小会正确更改。然后我再次滑动到第一个单元格,字体大小设置正确的字体大小。

因此,当 ViewController 加载时,UICollectionViewCell(称为 QuoteCell)中的 UITextView 字体大小为 20pt,但必须为 36pt。但是如果不滑动到另一个单元格并向后滑动,我就无法设置这个大小。

我试图在 awakeFromNib 和 willDisplayCell 或 cellForRowAtIndexPath 方法中设置字体。我也尝试使用 setNeedDisplay 但它没有用。

问题是什么?我忽略了什么?

// This codes adjust font size according to UITextView size.

extension UITextView {
func updateTextFont() {

    if (self.text.isEmpty || self.bounds.size.equalTo(CGSize.zero)) {
        print("Text Empty")
    }

    let textViewSize = self.frame.size
    let fixedWidth = textViewSize.width
    let expectSize = self.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat(MAXFLOAT)))

    var expectFont = self.font
    if (expectSize.height > textViewSize.height) {

        while (self.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat(MAXFLOAT))).height > textViewSize.height) {
            expectFont = self.font!.withSize(self.font!.pointSize - 1)
            self.font = expectFont
        }
    }
    else {
        while (self.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat(MAXFLOAT))).height < textViewSize.height) {

            expectFont = self.font!.withSize(self.font!.pointSize + 1)
            self.font = expectFont
        }
    }
}
}

我在 willDisplayCell 方法中设置了 txtQuote 文本大小。(我在 cellForRowAtIndexPath 和 awakeFromNib 方法中尝试了这个。)

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {

    let quoteCell = cell as! QuoteCell

    quoteCell.layer.masksToBounds = false
    quoteCell.txtQuote.updateTextFont()

}

标签: iosswiftuicollectionviewuitextview

解决方案


推荐阅读