【发布时间】:2022-01-25 08:11:36
【问题描述】:
对于我的消息功能的 ChatLogController,我无法让消息气泡根据其 textView 内容大小自动调整其大小。它仅显示 textview 中的一行,因为其余文本被截断。下面是我如何定义我的 textView 和消息 bubbleContainer:
private let textView: UITextView = {
let tv = UITextView()
tv.backgroundColor = .clear
tv.font = .systemFont(ofSize: 16)
tv.isScrollEnabled = false
tv.isEditable = false
tv.textColor = .white
return tv
}()
private let bubbleContainer: UIView = {
let view = UIView()
view.backgroundColor = .systemPurple
return view
}()
以下是限制条件:
addSubview(bubbleContainer)
bubbleContainer.layer.cornerRadius = 12
bubbleContainer.anchor(top: topAnchor, bottom: bottomAnchor)
bubbleContainer.widthAnchor.constraint(lessThanOrEqualToConstant: 250).isActive = true
bubbleLeftAnchor = bubbleContainer.leftAnchor.constraint(equalTo: profileImageView.rightAnchor, constant: 12)
bubbleLeftAnchor.isActive = false
bubbleRightAnchor = bubbleContainer.rightAnchor.constraint(equalTo: rightAnchor, constant: -12)
bubbleRightAnchor.isActive = false
bubbleContainer.addSubview(textView)
textView.anchor(top: bubbleContainer.topAnchor, left: bubbleContainer.leftAnchor,
bottom: bubbleContainer.bottomAnchor, right: bubbleContainer.rightAnchor,
paddingTop: 4, paddingLeft: 12, paddingBottom: 4, paddingRight: 12)
ChatLogController 是一个 UICollectionViewController,这是我设置 sizeForItemAt 的方式:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 50)
let estimatedSizeCell = MessageCell(frame: frame)
estimatedSizeCell.message = messages[indexPath.row]
estimatedSizeCell.layoutIfNeeded()
let targetSize = CGSize(width: view.frame.width, height: 1000)
let estimatedSize = estimatedSizeCell.systemLayoutSizeFitting(targetSize)
return .init(width: view.frame.width, height: estimatedSize.height)
}
委托设置为 self 但似乎甚至没有调用该函数。 在下面的图片中,您可以看到消息是如何被截断的,并且单元格高度被固定在 50 像素,它应该已经被调整以显示消息的其余部分:
【问题讨论】:
-
你为什么使用 textview,使用行数为 0 的标签会起作用
-
@GopiDonga 所以我只是尝试使用标签,现在什么都没有显示。你能分享一下你是如何构建标签的吗?
-
带有标签的单元格,其前导约束大于 90,其他所有边为 0
标签: swift uicollectionview textview messaging