gpt4 book ai didi

swift - 估计某些文本的 UICollectionView 单元格的大小

转载 作者:搜寻专家 更新时间:2023-11-01 06:34:39 24 4
gpt4 key购买 nike

所以我正在创建一个消息传递类型的应用程序,它由一些包含不同长度文本的 UITextView block 组成,这些 block 位于“气泡”UIView 中。

let textView: UITextView = {
let text = UITextView()
text.text = "SAMPLE"
text.translatesAutoresizingMaskIntoConstraints = false
text.backgroundColor = .clear
text.textColor = .white
return text
}()
let bubbleView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(r: 0, g: 137, b: 247)
view.layer.cornerRadius = 14
view.layer.masksToBounds = true
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var bubbleWidthAnchor: NSLayoutConstraint?

bubbleView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true
bubbleView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
bubbleWidthAnchor = bubbleView.widthAnchor.constraint(equalToConstant: 250)
bubbleWidthAnchor?.isActive = true
bubbleView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true

textView.leftAnchor.constraint(equalTo: bubbleView.leftAnchor, constant: 8).isActive = true
textView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
textView.rightAnchor.constraint(equalTo: bubbleView.rightAnchor).isActive = true
textView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true

为了设置单元格的高度,我使用了一个自定义函数,该函数 应该 无法正常工作。

自定义函数:

private func estimatedFrameForText(text: String) -> CGRect {
let size = CGSize(width: 250, height: 250)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)

return NSString(string: text).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 16)], context: nil)
}

我在 UICollectionViewsizeForItemAt 函数中调用:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
var height: CGFloat = 80 //Arbitrary number
if let text = messages[indexPath.item].text {
height = estimatedFrameForText(text: text).height + 8
}
return CGSize(width: view.frame.width, height: height)
}

我遇到的一个简单问题是……效果不佳: Example

知道我哪里出错了,或者有更好的解决方案来根据文本获得单元格所需的估计大小吗?

最佳答案

事实证明,我所缺少的只是在 textView 中设置文本大小。

需要放入 text.font = UIFont.systemFont(ofSize: 16) 因为获取估计大小的函数有:

attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 16)

因此您必须将两者定义为相同。

关于swift - 估计某些文本的 UICollectionView 单元格的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42865078/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com