我试图用一些文本初始化一个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
}
}
您不希望在初始化程序中传递字符串。单元格被重用,您需要更新现有单元格。正常创建单元格,然后在tltleLbl
中单独更新cellForRowAt
属性。
就像是:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "whatever" for: indexPath)
cell.titleLbl.text = // whatever value is appropriate for this row
return cell
}