Выполнение Segue для нового viewcontroller - подготовка к segue не удалась swift 5 - PullRequest
0 голосов
/ 03 ноября 2019

Я пытаюсь выполнить segue другому UIViewController.

Я хочу передать данные этому новому контроллеру. Тем не менее, похоже, что UILabels нового UIViewController еще не инициализированы, поэтому я ошибаюсь, утверждая, что я развертываю необязательное значение nil.

Чего мне не хватает?

Вот мой код:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
    let cell = collectionView.cellForItem(at: indexPath)
    collectionView.deselectItem(at: indexPath, animated: true)

    performSegue(withIdentifier: "addProductSegue", sender: cell)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    if let nextViewController = segue.destination as? AddProductsViewController
    {
        let productCell = sender as! ProductCell

        nextViewController.productName!.text = productCell.product!.Name
        nextViewController.priceForKg!.text = "\(productCell.product?.priceForKg ?? 0.0)"
        nextViewController.productImage!.image = productCell.productImageView.image
    }
}

И новый UIViewController:

import UIKit

class AddProductsViewController: UIViewController
{
    @IBOutlet weak var productName: UILabel!
    @IBOutlet weak var priceForKg: UILabel!
    @IBOutlet weak var productImage: UIImageView!

    override func viewDidLoad()
    {
        super.viewDidLoad()
    }

    @IBAction func addProduct(_ sender: UIButton)
    {
        self.navigationController?.popViewController(animated: true)
    }
}

1 Ответ

1 голос
/ 04 ноября 2019

вам нужно создать отдельные значения для каждого из элементов, которые вы хотите добавить, и затем использовать их во втором контроллере вида

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
    let cell = collectionView.cellForItem(at: indexPath)
    collectionView.deselectItem(at: indexPath, animated: true)

    performSegue(withIdentifier: "addProductSegue", sender: cell)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    if let nextViewController = segue.destination as? AddProductsViewController
    {
        let productCell = sender as! ProductCell

        nextViewController.productNameText = productCell.product!.Name
        nextViewController.priceForKgText = "\(productCell.product?.priceForKg ?? 0.0)"
        nextViewController.productImageImage = productCell.productImageView.image
    }
}

А во втором ViewController есть:

import UIKit

class AddProductsViewController: UIViewController
{
    @IBOutlet weak var productName: UILabel!
    @IBOutlet weak var priceForKg: UILabel!
    @IBOutlet weak var productImage: UIImageView!
//The elements you will reference in your prepare for segue
    var productNameText = ""
    var priceForKgText = ""
    var productImageImage : UIImage?
    override func viewDidLoad()
    {
        super.viewDidLoad()
//Call the function
        setupViews() 
    }

    func setupViews(){ //create a function that handles the ui update once the objects are initialized
     productName.text = productNameText
     priceForKg.text = priceForKgText
     guard let image = productImageImage else {
     return
     }
     productImage.image = image
    }

    @IBAction func addProduct(_ sender: UIButton)
    {
        self.navigationController?.popViewController(animated: true)
    }
}
...