[英]Why is my collectionView nil when using a delegate?
我有一個包含 2 個 CollectionViews 的 TableView,每個 CollectionViews 在一個 TableViewCells 中。 當我 select 第一個 CollectionView 中的一個項目時,我想更新第二個 CollectionView。 我正在使用委托模式,但它不起作用,因為當我想使用 .reloadData 方法時,我的第二個 CollectionView 似乎為零,但是為什么以及如何在第一個 CollectionView 中選擇項目時更新第二個 CollectionView?
protocol TableViewCellDelegate {
func update()}
class TableViewCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
var delegate: TableViewCellDelegate?
//...
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.delegate = ExistingInterestsCell() as? TableViewCellDelegate
delegate?.update()}}
class ExistingInterestsCell: UITableViewCell, TableViewCellDelegate {
func update() {
collectionView.reloadData()
}}
錯誤信息是:
致命錯誤:在隱式展開可選值時意外發現 nil:文件 Suggest_Accounts_and_Docs/ExistingInterestsCell.swift,第 13 行
這是使用協議/委托模式的錯誤方式。 您正在創建彼此過於依賴的類。
更好的方法是讓您的第一行告訴 controller它的一個集合視圖單元格被選中,然后允許 controller 更新用於第二行的數據,然后重新加載該行。
因此,您的“第一行”單元格將包含以下內容:
class FirstRowTableViewCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
var didSelectClosure: ((Int) -> ())?
var collectionView: UICollectionView!
// cell setup, collection view setup, etc...
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// tell the controller that a collection view cell was selected
didSelectClosure?(indexPath.item)
}
}
您的“第二行”單元格將包含以下內容:
class SecondRowTableViewCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
var collectionView: UICollectionView!
var activeData: [String] = []
// cell setup, collection view setup, etc...
}
在您的表格視圖 controller 中,您將擁有一個 var,例如:
var dataType: Int = 0
你的cellForRowAt
看起來像這樣:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let c = tableView.dequeueReusableCell(withIdentifier: "firstRowCell", for: indexPath) as! FirstRowTableViewCell
// set the closure so the first row can tell us one of its
// collection view cells was selected
c.didSelectClosure = { [weak self] i in
guard let self = self else { return }
// only reload if different cell was selected
if i != self.dataType {
self.dataType = i
self.tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: .automatic)
}
}
return c
}
let c = tableView.dequeueReusableCell(withIdentifier: "secondRowCell", for: indexPath) as! SecondRowTableViewCell
switch dataType {
case 1:
c.activeData = numberData
case 2:
c.activeData = wordData
default:
c.activeData = letterData
}
c.collectionView.reloadData()
return c
}
這是一個完整的例子......
第一行表格單元格
class FirstRowTableViewCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
var didSelectClosure: ((Int) -> ())?
var collectionView: UICollectionView!
let myData: [String] = [
"Letters", "Numbers", "Words",
]
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() -> Void {
let fl = UICollectionViewFlowLayout()
fl.scrollDirection = .horizontal
fl.minimumInteritemSpacing = 8
fl.minimumLineSpacing = 8
fl.estimatedItemSize = CGSize(width: 80.0, height: 60)
collectionView = UICollectionView(frame: .zero, collectionViewLayout: fl)
collectionView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(collectionView)
let g = contentView.layoutMarginsGuide
// to avoid auto-layout warnings
let hConstraint = collectionView.heightAnchor.constraint(equalToConstant: 60.0)
hConstraint.priority = .defaultHigh
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: g.topAnchor),
collectionView.leadingAnchor.constraint(equalTo: g.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: g.bottomAnchor),
hConstraint,
])
collectionView.register(SingleLabelCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = .systemBlue
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return myData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let c = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! SingleLabelCollectionViewCell
c.theLabel.text = myData[indexPath.item]
return c
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// tell the controller that a collection view cell was selected
didSelectClosure?(indexPath.item)
}
}
第二行表格單元格
class SecondRowTableViewCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
var collectionView: UICollectionView!
var activeData: [String] = []
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() -> Void {
let fl = UICollectionViewFlowLayout()
fl.scrollDirection = .horizontal
fl.minimumInteritemSpacing = 8
fl.minimumLineSpacing = 8
fl.estimatedItemSize = CGSize(width: 80.0, height: 60)
collectionView = UICollectionView(frame: .zero, collectionViewLayout: fl)
collectionView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(collectionView)
let g = contentView.layoutMarginsGuide
// to avoid auto-layout warnings
let hConstraint = collectionView.heightAnchor.constraint(equalToConstant: 60.0)
hConstraint.priority = .defaultHigh
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: g.topAnchor),
collectionView.leadingAnchor.constraint(equalTo: g.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: g.trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: g.bottomAnchor),
hConstraint,
])
collectionView.register(SingleLabelCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = .systemRed
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return activeData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let c = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! SingleLabelCollectionViewCell
c.theLabel.text = activeData[indexPath.item]
return c
}
}
表視圖 Controller
class MyTableViewController: UITableViewController {
let numberData: [String] = [
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15",
]
let letterData: [String] = [
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O",
]
let wordData: [String] = [
"First", "Second", "Third", "Fourth", "Fifth", "Sixth",
]
var dataType: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(FirstRowTableViewCell.self, forCellReuseIdentifier: "firstRowCell")
tableView.register(SecondRowTableViewCell.self, forCellReuseIdentifier: "secondRowCell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let c = tableView.dequeueReusableCell(withIdentifier: "firstRowCell", for: indexPath) as! FirstRowTableViewCell
// set the closure so the first row can tell us one of its
// collection view cells was selected
c.didSelectClosure = { [weak self] i in
guard let self = self else { return }
// only reload if different cell was selected
if i != self.dataType {
self.dataType = i
self.tableView.reloadRows(at: [IndexPath(row: 1, section: 0)], with: .automatic)
}
}
return c
}
let c = tableView.dequeueReusableCell(withIdentifier: "secondRowCell", for: indexPath) as! SecondRowTableViewCell
switch dataType {
case 1:
c.activeData = numberData
case 2:
c.activeData = wordData
default:
c.activeData = letterData
}
c.collectionView.reloadData()
return c
}
}
集合視圖單元(由兩行使用)
// simple single-label collection view cell
class SingleLabelCollectionViewCell: UICollectionViewCell {
let theLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() -> Void {
theLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(theLabel)
let g = contentView.layoutMarginsGuide
NSLayoutConstraint.activate([
theLabel.topAnchor.constraint(equalTo: g.topAnchor),
theLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor),
theLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor),
theLabel.bottomAnchor.constraint(equalTo: g.bottomAnchor),
])
theLabel.backgroundColor = .yellow
contentView.layer.borderColor = UIColor.green.cgColor
contentView.layer.borderWidth = 1
}
}
結果:
點擊“數字”,我們看到:
點擊“單詞”,我們看到:
這條線
self.delegate = ExistingInterestsCell() as? TableViewCellDelegate
指一個帶有 nil 插座的表格單元格,這就是它崩潰的原因,您需要訪問一個真實呈現的單元格
編輯:在兩個單元格類中添加對 tableView 的引用,並使用 indexPath 和表格獲取所需的單元格並更新它的集合
if let cell = table.cellForRow(at:Indexpath(row:0,section:0)) as? ExistingInterestsCell {
// update model
cell.collectionView.reloadData()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.