CollectionViewCell未显示TextView:自定义chatMessageCell代码求助
排查ChatMessageCell中TextView不显示的问题
我来帮你揪出这个TextView不显示的问题,大概率是踩了AutoLayout的几个常见坑,咱们一步步来分析:
常见问题点
- 未禁用自动转换约束:所有用代码创建的UI控件默认都开启了
translatesAutoresizingMaskIntoConstraints = true,这会让系统自动生成一套约束,和你自定义的约束打架,直接导致你的布局被覆盖,TextView自然显示不出来。 - 约束不完整:你的代码里
widthAnchor.constra...明显没写完,而且缺少高度相关的约束,AutoLayout需要完整的约束来计算控件的frame,约束不全的话控件会被压缩到0尺寸。
修正后的完整代码
class ChatMessageCell: UICollectionViewCell { let textView: UITextView = { let tv = UITextView() tv.text = "SAMPLE TEXT" tv.font = UIFont.systemFont(ofSize: 16) // 核心修复:禁用系统自动生成的约束 tv.translatesAutoresizingMaskIntoConstraints = false // 可选优化:消息展示用的TextView一般不需要编辑和滚动 tv.isEditable = false tv.isScrollEnabled = false tv.showsVerticalScrollIndicator = false return tv }() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .red addSubview(textView) // 补全所有必要约束,这里给TextView加了16的左右边距和8的上下边距,你可以根据需求调整 NSLayoutConstraint.activate([ textView.rightAnchor.constraint(equalTo: rightAnchor, constant: -16), textView.topAnchor.constraint(equalTo: topAnchor, constant: 8), textView.leftAnchor.constraint(equalTo: leftAnchor, constant: 16), textView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8) ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
额外提醒
别忘了在CollectionView注册cell的时候用对类名,比如:
collectionView.register(ChatMessageCell.self, forCellWithReuseIdentifier: "ChatMessageCell")
如果需要让cell自适应高度,记得给CollectionView的FlowLayout设置:
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize }
内容的提问来源于stack exchange,提问作者Dario Da
相关产品推荐
相关产品推荐

