I have prepared a segue but when the user selects a cell it is not pass label text to text in detail View
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "viewNumberSegue" {
guard let indexPath = sender as? IndexPath else { return }
let collectionCell = collectionView.cellForItem(at: indexPath) as! ItemCollectionViewCell
let textToPass = collectionCell.ItemLabel.text
let detailVC = segue.destination as? DetailViewController
detailVC?.number = textToPass!
}
}
// MARK: UICollectionViewDelegate
extension GridCollectionViewController {
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "viewNumberSegue", sender: indexPath)
}
}
DetailVC
import UIKit
class DetailViewController: UIViewController {
var number:String = ""
@IBOutlet weak var numberLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
print(number)
numberLabel.text = number
}
}
CodePudding user response:
Instead of passing the indexPath in sender, it's better to directly pass the number as sender.
extension GridCollectionViewController {
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let collectionCell = collectionView.cellForItem(at: indexPath) as! ItemCollectionViewCell
let textToPass = collectionCell.ItemLabel.text
self.performSegue(withIdentifier: "viewNumberSegue", sender: textToPass)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "viewNumberSegue" {
guard let number = sender as? String else { return }
let detailVC = segue.destination as? DetailViewController
detailVC?.number = number
}
}