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

时间:2017-03-25 11:26:43

标签: swift uicontainerview childviewcontroller parentviewcontroller

我目前正在使用容器视图,我想使用委托通过子视图控制器更改父视图控制器imageView的值,但它总是返回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!")
        }
    }
}

1 个答案:

答案 0 :(得分:0)

删除此行:

nextView.image = image

并将userIsDone功能更改为:

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

hello

附注:

  • 在Swift中,您不需要在块/闭包之外使用self。例如,您不需要self.imageView.image = self.image - 只需imageView.image = image即可。
  • 协议应该是大写的,例如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!)
    }
}