IBOutlet: неожиданно найден ноль при неявном развертывании необязательного значения - PullRequest
0 голосов
/ 21 мая 2019

Я правильно подключил свой TableView к своему CollectionViewCell с помощью IBOutlet, но когда я пытаюсь что-то сделать с этим табличным представлением, например: cell.tableview.tag = x, он говорит:

Неожиданно найден ноль, в то время как неявноразвертывание необязательного значения.Когда я раскомментирую

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
    }
}

1 Ответ

1 голос
/ 21 мая 2019

Удалите эту строку из вашего метода viewDidLoad.

collectionView.register(CollectionCell.self, forCellWithReuseIdentifier: "CollectionCell")

Используется для регистрации программно созданной ячейки представления коллекции в представлении коллекции.Если вы используете этот метод, когда у вас есть все в раскадровке, он создаст ячейку, где его IBOutlets равны нулю.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...