【发布时间】:2019-03-15 02:45:56
【问题描述】:
我在尝试用一些文本初始化 UICollectionViewCell 子类时遇到了困难:(我当然对初始化程序很陌生,我通常的蹩脚解决方法(一般用于传递数据,而不是用于单元格)是调用设置函数以在之后传递信息。任何明智的话?非常感谢。
class MainCell: UICollectionViewCell {
let titleLbl: UILabel = {
let lbl = UILabel() // other stuff was in here
lbl.text = "Placeholder text"
return lbl
}()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
func setupViews() {
// adding to subviews, constraints, etc. Placeholder text works.
}
}
class SubCell: MainCell {
convenience init(title: String) {
self.init()
titleLbl.text = title
}
}
SubCell(title: "Test") // doesn't return a cell with "Test" in the label
已解决: 想分享我的解决方案,以防它可以帮助某人。正如@rmaddy 指出的那样,我正在使未使用我的字符串初始化的单元格出列。
我见过这些通常基于数组并以这种方式传递数据。但是我有 4 个具有不同元素的单元格,如果可能的话,我想避免使用 indexPath 逻辑。
我的解决方案(我确定我不是唯一的,但我在任何地方都找不到)是为每个单元格创建自定义类,例如视图控制器的工作方式。现在我有一个包含单元格的数组,如果我需要添加一个新单元格,我会创建单元格类并将其添加到列表中,而不会弄乱任何 cellId 或 indexPath 的东西。对不起,我很新,我真的很兴奋。如果有人想烤它,这是我的代码:
class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let cells = [CellOne(), CellTwo(), CellThree(), CellFour()]
// subclasses of UICollectionViewCell, defined elsewhere
override init(collectionViewLayout layout: UICollectionViewLayout) {
super.init(collectionViewLayout: layout)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView.backgroundColor = bgColor
for cell in cells {
collectionView.register(type(of: cell), forCellWithReuseIdentifier: String(describing: type(of: cell)))
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return collectionViewCellSize
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cells.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cellType = type(of: cells[indexPath.item])
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: cellType), for: indexPath)
return cell
}
}
【问题讨论】:
标签: ios swift uicollectionview initialization init