ios - CollectionViewCell 不显示 TextView

标签 ios xcode uicollectionview uicollectionviewcell

我有一个自定义的 Collection View 单元格:

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。我做错了什么?

最佳答案

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

self.addSubview(textView)

试试这个:

self.contentView.addSubview(textView)

关于ios - CollectionViewCell 不显示 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50172701/

相关文章:

ios - swift 中的协议(protocol)引用抛出段错误 11

objective-c - 上载音频-HTTP流

iphone - ios 6 - 在无法在设备上运行的应用程序中发布到 Facebook

ios - Swift: Collection View 未正确调整以更改大小

swift - 在 UICollectionView 中选择单个 UILabel

ios - 默认情况下直接添加到数组

php - 如何使用PHP和mysql数据库在XCode中成功登录后重定向到新 View

ios - Xcode 9 代码片段错误

iOS 无法更新 Xcode 7.1

swift - 以编程方式增加 indexPath