Swift / iOS8:在Segue之前为下一个View Controller设置imageView

时间:2015-01-13 10:27:03

标签: ios swift uiimageview

取决于几个参数我试图在第二个VC上设置一个Image,但不知何故它总是返回null ??

这就是我的所作所为:

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

        if segue.identifier == "showDetail"  {
            println("going forth!")
            println(self.myButton.selected)

            let controller = segue.destinationViewController as? DetailVC

            if myButton.selected == true {
                var newImage = UIImage(named:"Test1")
                var oldImage = controller?.imageView.image
                println(oldImage)

                oldImage = newImage
            } else {
                var newImage = UIImage(named:"Test2")
                var oldImage = controller?.imageView.image
                println(oldImage)

                oldImage = newImage
            }

        } else {
            println("roflcopter")
        }
    }

细节VC基本上没有"没有":

import UIKit

class DetailVC: UIViewController {


    @IBOutlet weak var imageView: UIImageView!

    var testString:String!

    @IBAction func goBacktoMain(segue: UIStoryboardSegue) {

        println("going back")

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        println("view Did Load")
        println(testString)
    }

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

}

第二个VC有一个通过Storyboard设置的默认图像,但当我停止使用断点@let控制器时,它会告诉我imageview实际上是null,只有在详细信息vc显示一次后才会设置吗?

€dit:设置字符串并在第二个VC上打印它完全正常

2 个答案:

答案 0 :(得分:7)

你在哪里设置图像? 在prepareForSegue内,UIImageView IBOutlet将无法加载。您必须在DetailVC类中声明图像变量,如下所示,并在viewDidLoad中设置该图像。

class  DetailVC
{
    var image:UIImage? = nil
    @IBOutlet weak var imageView: UIImageView!

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

prepareSegue功能中,设置

let controller = segue.destinationViewController as? DetailVC
controller?.image = //Your Image according to conditions.

答案 1 :(得分:1)

在目标segue中声明一个UIImage变量,将图像对象传递给它。

在目标对象上的viewDidLoad上,将图像指定给imageView.Image属性

最有可能的是Outlet尚未初始化