首页 > 解决方案 > 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。我究竟做错了什么?

标签: iosxcodeuicollectionviewuicollectionviewcell

解决方案


您应该将所有子视图添加到 UICollectionView 的 contentView,而不是添加到 UICollectionView 实例本身。所以代替这个:

self.addSubview(textView)

尝试这个:

self.contentView.addSubview(textView)

推荐阅读