我有一个自定义集合视图单元格:
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
}
但是,屏幕上只显示了许多红色单元格,但它们不包含任何文本或文本视图。我做错了什么?
答案 0 :(得分:2)
您应该将所有子视图添加到UICollectionView的contentView,而不是添加到UICollectionView实例本身。所以不要这样:
self.addSubview(textView)
试试这个:
self.contentView.addSubview(textView)