Невозможно добавить представление коллекции к двум контроллерам представления - PullRequest
0 голосов
/ 04 июля 2019

Я добавил коллекционное представление на два из моих контроллеров представления, и когда я нажимаю на ячейку в первом контроллере представления (TabBar.swift), оно должно перейти ко второму контроллеру представления и наоборот, но по какой-то причине приложение вылетает при запуске.

Вот код для первого контроллера представления: TabBar.swift

struct OpenViewController {
var viewController: UIViewController

}
class TabBar: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white
        addCollectionViewConstraints()
    }

    var viewControllerList = [
    OpenViewController(viewController: FirstScreen())
    ]

    // Setup the collection veiw

    let collectionView: UICollectionView = {

        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellID")
        cv.translatesAutoresizingMaskIntoConstraints = false
        return cv
    }()

    // Add constraints to the collection view
    func addCollectionViewConstraints() {

        view.addSubview(collectionView)
        collectionView.backgroundColor = .blue
        collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
        collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        collectionView.heightAnchor.constraint(equalTo: collectionView.widthAnchor, multiplier: 0.3).isActive = true

        collectionView.delegate = self
        collectionView.dataSource = self
    }

}

Вот код для второго контроллера вида: FirstScreen.swift

struct OpenViewControllerTwo {
    var viewController: UIViewController
}
class FirstScreen: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .yellow
        addCollectionViewConstraints()

    }

    var viewControllerList = [
        OpenViewControllerTwo(viewController: FirstScreen())
    ]

    let collectionView: UICollectionView = {

        let layout = UICollectionViewFlowLayout()
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellID")
        cv.translatesAutoresizingMaskIntoConstraints = false
        return cv
    }()

    // Add constraints to the collection view
    func addCollectionViewConstraints() {

        view.addSubview(collectionView)
        collectionView.backgroundColor = .blue
        collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
        collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        collectionView.heightAnchor.constraint(equalTo: collectionView.widthAnchor, multiplier: 0.3).isActive = true

        collectionView.delegate = self
        collectionView.dataSource = self
    }
}

extension FirstScreen: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

    // The number of elements inside the collection view
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }

    // Adding the cells
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath)

        // Customize the cells
        cell.backgroundColor = .black
        cell.layer.cornerRadius = collectionView.contentSize.height / 2
        cell.layer.borderWidth = 1
        cell.layer.borderColor = UIColor.black.cgColor

        return cell
    }

    // The witdth and the height of the cell
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.frame.height, height: collectionView.frame.height)
    }

    // Padding to the cells
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
    }

    // Selecting a cell and navigating to another view controller
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let openViewController = self.viewControllerList[indexPath.row]
        self.present(openViewController.viewController, animated: false)

    }

}

Журнал аварий:

Crash log

Ответы [ 2 ]

1 голос
/ 04 июля 2019

Вы получаете проблему с памятью, потому что viewControllerList инициализируется в циклах. Просто объявите переменную, как это

var viewControllerList = [OpenViewController]()

затем присвойте значение, как это в viewDidLoad.

viewControllerList = [
            OpenViewController(viewController: FirstScreen())
        ]
0 голосов
/ 04 июля 2019

Я нашел этот код в FirstScreen

var viewControllerList = [
    OpenViewControllerTwo(viewController: FirstScreen())
]

Когда FirstScreen init, viewControllerList будет инициализировать все вызовы FirstScreen. Создано рекурсивно-рекурсивно. Пожалуйста, измените код выше, поместите другой класс, например: In FirstClass

var viewControllerList = [
    OpenViewControllerTwo(viewController: SecondClass())
]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...