ios - 如何在 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()
}
解决方案
推荐阅读
- dart - 是否有 Dart Linter 规则强制字段返回类型和方法参数?
- php - Laravel/Angular“密码过期”身份验证流程
- amazon-web-services - 使用 aws cli 创建 cognito-user-pool 时出现“未知选项”错误
- python - 如何创建一个可下标的 Mock 对象?
- python - 不和谐.py | 删除空的语音通道
- oracle-sqldeveloper - Oracle SQL Developer 中的突然导出失败
- python - TypeError: 'int' 对象在渲染 Flask 模板时不可迭代
- android - Android Studio:Kotlin 注册监听器
- linux - 在 Dockerfile 中运行 chown 什么都不做
- powershell - 如何将此值获取到变量中以供以后操作?