I properly connected my TableView to my CollectionViewCell with an IBOutlet, but when I try to do something with this tableview, for example: cell.tableview.tag = x
, it says:
Unexpectedly found nil while implicitly unwrapping an Optional value. When I uncomment
import UIKit
class CollectionCell: UICollectionViewCell {
// When I uncomment the next line, it works good
//let tableView = UITableView()
@IBOutlet var tableView: UITableView!
}
class ViewController: UIViewController {
var testArray = [["Day0-0","Day0-1","Day0-2"], ["Day1-0","Day1-1","Day1-2"], ["Day2-0","Day2-1","Day2-2"],["Day3-0","Day3-1","Day3-2"],["Day4-0","Day4-1","Day4-2"]]
@IBOutlet weak var collectionView: UICollectionView!
// let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(CollectionCell.self, forCellWithReuseIdentifier: "CollectionCell")
view.addSubview(collectionView)
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[collectionView]|", options: [], metrics: nil, views: ["collectionView":collectionView]))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[collectionView]|", options: [], metrics: nil, views: ["collectionView":collectionView]))
}
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return testArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionCell
// Here is where i get the error: "Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value"
cell.tableView.tag = indexPath.item
cell.tableView.reloadData()
cell.tableView.delegate = self
cell.tableView.dataSource = self
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return collectionView.frame.size
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return testArray[tableView.tag].count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") ?? UITableViewCell(style: .default, reuseIdentifier: "Cell")
cell.textLabel?.text = testArray[tableView.tag][indexPath.row]
return cell
}
}