为什么值是零?

时间:2016-02-27 05:33:02

标签: ios swift

我将数据从一个类传递到另一个类,当我断点并查看控制台时,我收到的是nil值。

这是带有值的类,我想将这些值传递给类viewc

func viewControllerAtIndex(index: Int) -> viewc {
    if ((self.namepage.count == 0) || (index >= self.namepage.count) {
        return viewcard()           
    }

    var vc: viewc = self.storyboard?.instantiateViewControllerWithIdentifier("ItemController") as! viewc

    vc.imageFile = self.pageImages[index] //not nil
    vc.cTitle = self.namepage[index]      //not nil
    vc.nTitle = self.numberpage[index]    //not nil
    vc.pageIndex = index
    vc.getArray()

    return vc
}

这个类是我想要传递数据的类。

class viewc: UIViewController{
    var pageIndex: Int!
    var cTitle: String!
    var imageFile: String!
    var nTitle: String!

    @IBOutlet weak var imagen: UIImageView!
    @IBOutlet weak var name: UILabel!
    @IBOutlet weak var number: UILabel!

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

    func getArray() {
        self.imagen.image = UIImage(named: self.imageFile)//imageFile is nil
        self.name.text = self.cTitle//cTitle is nil
        self.number.text = self.nTitle//nTitle is nil
    }
}

2 个答案:

答案 0 :(得分:0)

func viewControllerAtIndex(index: Int) -> ViewC {
    var vc = self.storyboard?.instantiateViewControllerWithIdentifier("ItemController") as! ViewC

    vc.imageFile = self.pageImages[index]
    vc.cTitle = self.namepage[index]
    vc.nTitle = self.numberpage[index]
    vc.pageIndex = index

    vc.testProperties()

    return vc
}

class ViewC: UIViewController{
    var pageIndex: Int!
    var cTitle: String!
    var imageFile: String!
    var nTitle: String!

    @IBOutlet weak var imagen: UIImageView!
    @IBOutlet weak var name: UILabel!
    @IBOutlet weak var number: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        imagen.image = UIImage(named: imageFile)
        name.text = cTitle
        number.text = nTitle
    }

    // This will crash if one of them is nil
    func testProperties() {
        print("pageIndex: \(pageIndex)")
        print("cTitle: \(cTitle)")
        print("imageFile: \(imageFile)")
        print("nTitle: \(nTitle)")
    }
}

现在您的ViewC将正确设置。请注意,您只能在加载视图后访问IBOutlet。如果您需要在视图加载之前访问插座,则需要执行其他操作。

答案 1 :(得分:-2)

该功能应如下所示。

func viewControllerAtIndex(index: Int) -> UIViewController? 
{
    let vc = storyboard?.instantiateViewControllerWithIdentifier (pagesArray[index]) return vc 
}