【发布时间】: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