iOS - 如何通过子容器设置父视图控制器的图像视图?

iOS - How to set imageview of a parent view controller through child container?

我目前正在使用容器视图,我想使用委托通过子视图控制器更改父视图控制器 imageView 的值,但它总是 returns nil.

import UIKit

protocol updateImage {
    func userIsDone(image:UIImage)
}

class ViewController: UIViewController, updateImage{

    @IBOutlet weak var imageView:UIImageView!
    var image = UIImage(named: "hello.png")

    override func viewDidLoad() {
        super.viewDidLoad()
        self.imageView.image=self.image
    }

    func userIsDone(image: UIImage) {
        self.image=image
    }

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

        if segue.identifier == "containerChild"{

            let nextView = segue.destinationViewController as! ControllerChild
            nextView.image=self.image
            nextView.delegate=self
        }
    }
}

class ControllerChild:UIViewController{

    var image=UIImage(named: "newhello.png")
    var delegate: updateImage? = nil

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

    @IBAction func changeImage(sender:UIButton){

        if(delegate != nil){
            self.delegate!.userIsDone(self.image!)
            print("I am Called!")
        }
    }
}

删除这一行:

nextView.image = image

并将userIsDone函数更改为:

func userIsDone(image: UIImage) {
    imageView.image = image
}

旁注:

  • 在 Swift 中,您不需要在 blocks/closures 之外使用 self。例如,您不需要 self.imageView.image = self.image——只需 imageView.image = image 即可。
  • 协议应该是 upper-cased,比如 UpdateImage(而不是 updateImage)。
  • 您不需要额外的 .png 来引用图片,只需要标题,例如:"hello"

Apple 在其 awesome Swift book.

中描述了 Swift 代码约定

这是重构后的代码 (Swift 3):

import UIKit

protocol UpdateImageProtocol {
    func userIsDone(image: UIImage)
}

class ViewController: UIViewController, UpdateImageProtocol {

    @IBOutlet weak var imageView: UIImageView!
    var image = UIImage(named: "hello")

    override func viewDidLoad() {
        super.viewDidLoad()
        userIsDone(image: image!)
    }

    func userIsDone(image: UIImage) {
        imageView.image = image
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "containerChild" {
            let nextView = segue.destination as! ChildViewController
            nextView.delegate = self
        }
    }
}

class ChildViewController: UIViewController {

    var image = UIImage(named: "newHello")
    var delegate: UpdateImageProtocol?

    @IBAction func changeImage(sender: UIButton) {
        delegate?.userIsDone(image: image!)
    }
}