0

我目前正在使用容器视图,我想使用委托通过子视图控制器更改父视图控制器 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!")
        }
    }
}
4

1 回答 1

0

删除这一行:

nextView.image = image

并将userIsDone函数更改为:

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

你好

作为旁注:

  • 在 Swift 中,你不需要self在块/闭包之外使用。例如,您不需要self.imageView.image = self.image- 只需imageView.image = image要做。
  • 协议应该是大写的,比如UpdateImage(而不是updateImage)。
  • 您不需要额外.png的参考图像,只需要标题,例如:"hello"

Apple 在其出色的Swift 书籍中描述了 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!)
    }
}
于 2017-03-25T11:55:10.557 回答