ios - CollectionViewCell 不显示 TextView
问题描述
我有一个自定义集合视图单元格:
class chatMessageCell: UICollectionViewCell {
let textView : UITextView = {
let tv = UITextView()
tv.text = "SAMPLE TEXT"
tv.font = UIFont.systemFont(ofSize: 16)
return tv
}()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.red
self.addSubview(textView)
textView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
textView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
textView.widthAnchor.constraint(equalToConstant: 200).isActive = true
textView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
它也被注册:
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Chat"
collectionView?.delegate = self
collectionView?.dataSource = self
collectionView?.collectionViewLayout = UICollectionViewFlowLayout()
collectionView?.backgroundColor = UIColor.white
collectionView?.register(chatMessageCell.self, forCellWithReuseIdentifier: cellID)
}
并创建:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! chatMessageCell
let message = messages[indexPath.item]
cell.textView.text = message.text
return cell
}
但是,屏幕上只出现了一些红色单元格,但它们不包含任何文本或 textView。我究竟做错了什么?
解决方案
您应该将所有子视图添加到 UICollectionView 的 contentView,而不是添加到 UICollectionView 实例本身。所以代替这个:
self.addSubview(textView)
尝试这个:
self.contentView.addSubview(textView)
推荐阅读
- javascript - 如何从nodejs中的工作线程修改全局变量
- javascript - 如何在同一页面上使用具有相同 id 的多个滑块?
- git - 如何将 repo 从 github 迁移到 gitlab?
- reactjs - createAsyncThunk:在使用获取的数据更新存储后,在同一个有效负载创建器中调度更多操作
- delphi - 如何解析自定义格式的数据?
- java - 如何将流用于具有多个条件检查的逻辑?
- python - 使用字典键和值重现嵌套列表/元组结构
- node.js - Docker NPM 无法从 Github 获取私有模块/仓库
- c++ - 如何在 SFML 窗口中制作网格?
- python - 搜索在给定列表中一次将一个字符串转换为另一个字符串的最短方法