CollectionViewCell не показывает TextView - PullRequest
0 голосов
/ 04 мая 2018

У меня есть пользовательская ячейка просмотра коллекции:

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
}

Однако на экране появляется только несколько красных ячеек, но они не содержат текст или текстовое представление. Что я делаю не так?

1 Ответ

0 голосов
/ 04 мая 2018

Вы должны добавить все подпредставления в contentView UICollectionView, а не в сам экземпляр UICollectionView. Так что вместо этого:

self.addSubview(textView)

Попробуйте это:

self.contentView.addSubview(textView)
...