我目前正在使用容器视图,我想使用委托通过子视图控制器更改父视图控制器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!")
}
}
}
答案 0 :(得分:0)
删除此行:
nextView.image = image
并将userIsDone
功能更改为:
func userIsDone(image: UIImage) {
imageView.image = image
}
附注:
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!)
}
}