【问题标题】:CollectionViewCell not showing TextViewUICollectionViewCell 不显示 UITextView
【发布时间】:2018-05-04 10:24:34
【问题描述】:

我有一个自定义集合视图单元格:

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

【问题讨论】:

  • 覆盖awakeFromNib 方法。将代码从init 方法写入它。
  • 这没有帮助。我的意思是 - 设置了红色背景颜色,因此该方法似乎有效并被调用。但是为什么我在单元格上看不到任何 textView?
  • 嗨,有效果吗?

标签: ios xcode uicollectionview uicollectionviewcell


【解决方案1】:

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

self.addSubview(textView)

试试这个:

self.contentView.addSubview(textView)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 2013-03-23
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    相关资源
    最近更新 更多