协议和代表不工作..我做错了什么?

时间:2015-12-04 20:51:12

标签: ios swift delegates uicollectionview protocols

我正在尝试通过委托和协议将我的collectionViewCell imageView中的图像发送到另一个VC中的imageView。我无法弄清楚为什么这不能正常工作?

发送VC为:TrainersViewController 收到的VC是:BioViewController

这是我的协议:

protocol TrainersViewControllerDelegate: class {

    func trainersViewController(controller: TrainersViewController, didFinishSendingImage trainer:TrainerArray)
}


class TrainersViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, AddNewTrainerViewControllerDelegate {

    weak var delegate: TrainersViewControllerDelegate? 
}

这是我的接收课程:

class BioViewController: UIViewController, TrainersViewControllerDelegate {


    @IBAction func backToTrainersButton(sender: AnyObject) {

        dismissViewControllerAnimated(true, completion: nil)
    }

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

    @IBOutlet weak var bioImage: UIImageView!


    func trainersViewController(controller: TrainersViewController, didFinishSendingImage trainer: TrainerArray) {

        trainer.trainerImage! = bioImage as! UIImage
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if segue.identifier == "bioSegue" {
            let navigationController = segue.destinationViewController as! UINavigationController
            let controller = navigationController.topViewController as! TrainersViewController
            controller.delegate = self
        }
    }
}

最后,这是我正在呼吁实现这一目标的collectionViewCell中的按钮:

    @IBAction func bioSegueButton(sender: AnyObject) {
    let index = sender.tag
    let trainer = trainers[index]
    print(trainer.name)
    delegate?.trainersViewController(self, didFinishSendingImage: trainer)
    performSegueWithIdentifier("bioSegue", sender: self)
}

为什么这不会将我的图像发送到另一个VC的imageView中?

2 个答案:

答案 0 :(得分:0)

在你打电话的时候

delegate?.trainersViewController(self, didFinishSendingImage: trainer)

变量delegate尚未设置。您可以使用以下行检查:

print(delegate)

如果代理人未设置,则此行将打印nil

答案 1 :(得分:0)

你可以在prepareForSegue中传递图像,这是最简单的方法(但你必须在sending类中实现它)。以前的答案是正确的。您在设置委托之前使用它。如果你真的想要使用它,我会首先执行segue,在准备它时你设置委托,然后尝试使用委托方法。

@IBAction func bioSegueButton(sender: AnyObject) {
    let index = sender.tag
    let trainer = trainers[index]
    print(trainer.name)
    performSegueWithIdentifier("bioSegue", sender: self)
    delegate?.trainersViewController(self, didFinishSendingImage: trainer)
}

这可能会导致另一个问题,但这不是关于授权:)

您可以尝试撤销您的代表团。在BioViewController make BioViewControllerDelegate中使用方法bioViewControllerSetUpImage(bioViewController: BioViewController) -> UIImage在发送类中实现它,并在BioViewController类中调用它,例如viewDidLoad中的bioImage = delegate?.bioViewControllerSetUpImage(self)。然后创建BioViewController,设置委托,segue。 (但这是我试图解决它的问题,随意忽略它)