如何将选定的集合视图单元格发送到另一个视图控制器(ios)?

时间:2017-05-19 11:08:13

标签: ios swift3

我能够在我的集合视图中检测选定的行(图像),但我需要将其发送到另一个视图控制器。以下是代码的一部分:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? CollectionViewCell {

        cell.cellImage.image = UIImage(named: images[indexPath.row])
        return cell
    } else {
        return CollectionViewCell()

    }
}

//Printinig the selected image ID in console
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
    SelectedItem = indexPath.row + 1
    print(SelectedItem)
}

//Navigate to MPViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let DestViewController = segue.destination as!  MPViewController
    DestViewController.labelText = String(SelectedItem)
}
}

3 个答案:

答案 0 :(得分:0)

在目标类中获取一个实例变量,并在准备segue时设置它的值,然后在viewDidload中将该字符串设置为标签的文本,如

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let DestViewController = segue.destination as!  MPViewController
    DestViewController.yourText = String(SelectedItem) 
 }

ans viewDidload

  yourLabel.text = yourText

答案 1 :(得分:0)

//Printinig the selected image ID in console

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
    self.SelectedItem = indexPath.row + 1

    self.selectedImage = UIImage(named: images[indexPath.row]);

    print(SelectedItem)
}

//Navigate to MPViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let DestViewController = segue.destination as!  MPViewController
    DestViewController.imageSelected = self.selectedImage;
    DestViewController.selectedItem = String(self.SelectedItem);

}

现在,在MPViewController中,您可以根据需要使用数据self.imageSelected和self.selectedItem。

答案 2 :(得分:0)

首先初始化变量

var imageToPass:UIImage!

然后更新didSelectItemAt func

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
    SelectedItem = indexPath.row + 1
    print(SelectedItem)

    self.imageToPass = UIImage(named: images[SelectedItem])

    performSegue(withIdentifier: "TargetVC", sender: imageToPass) //here you give the identifier of target ViewController
}

转到TargetVC并初始化变量

var getImage:UIImage!

然后覆盖之前VC中的功能

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "TargetVC" {

            if let targetVC = segue.destination as? TargetVC {

                if let imageToPass = sender as? UIImage {

                    TargetVC.getImage = imageToPass

                }

            }

        }
    }