Hello. Help solve. The task is to transfer the name with or without the button from tableViewController to the header of collectionViewController . I understand that my variable takes nil , but where it takes and how to fix it already broke my head and I can not cope. I am a novice, so do not judge strictly. Here is the code:

 class ViewController: UITableViewController { var file: File! var files: [File] = [File(name: "name1", address: "address1", image: ""), File(name: "name2", address: "address2", image: "")] override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let dvc = segue.destination as? CollectionViewController { let indexPath = tableView.indexPathForSelectedRow?.row if indexPath == nil { dvc.files2 = files[indexPath!] } else { print("error") } } } class CollectionViewController: UICollectionViewController { var files2: File! override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath) as! Header header.nameLabel.text = files2!.name header.addressLabel.text = "address" return header } 

    1 answer 1

    Try this:

     class ViewController2: UITableViewController { var file: File! var files: [File] = [File(name: "name1", address: "address1", image: ""), File(name: "name2", address: "address2", image: "")] override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let dvc = segue.destination as? CollectionViewController { if let indexPath = tableView.indexPathForSelectedRow { let row = indexPath.row assert(row < files.count) dvc.file2 = files[row] } } else { print("error") } } // ... } class CollectionViewController: UICollectionViewController { var file2: File? override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "Header", for: indexPath) as? Header, let file = self.file2 { header.nameLabel.text = file.name header.addressLabel.text = file.address return header } else { return UICollectionReusableView() } } // ... } 
    • Thank you, but it did not work out (( - Dmitry Denikayev