如何从xib调用performSegueWithIdentifier?

时间:2016-03-18 22:48:22

标签: ios swift view segue xib

我有一个带有segue的viewController到名为“toSecond”的secondViewController。 在viewController中我加载customView.xib

let myCustomView = NSBundle.mainBundle().loadNibNamed("customView", owner: self, options: nil)[0]

在这个customView中我有一个带动作的按钮:

viewController().goToSecond()
在viewController中的

我有这个代码的函数

func goToSecond() {
self.performSegueWithIdentifier("toSecond", sender: self)
}

但是当我在customView中按下按钮时,我变成了一个错误:

  

viewController没有带标识符'toSecond'的segue

当我直接从viewController调用这个函数时,所有工作都很棒!

那么,如何从我的customView调用performSegueWithIdentifier?

customView源代码:

import UIKit

class customView: UIView {

@IBAction func ToSecondButton(sender: AnyObject) {
viewController().goToSecond() }

}

viewController源代码:

import UIKit

class viewController: UIViewController {

...
let myCustomView = NSBundle.mainBundle().loadNibNamed("customView", owner: self, options: nil)[0]
self.view.addSubview(myCustomView)
func goToSecond() {
    self.performSegueWithIdentifier("toSecond", sender: self)
    }
...

}

1 个答案:

答案 0 :(得分:2)

问题是您的UIView子类正在调用viewController().goToSecond()。那不符合你的想法。 viewController()没有引用加载自定义视图的视图控制器。它实例化了该类的第二个孤立实例(未连接到任何故事板),因此无法找到segue。

如果你真的要让这个自定义UIView子类启动一个segue,你需要将对原始视图控制器的引用传递给自定义视图。因此,向自定义视图子类添加一个属性,该子类可以保存对其视图控制器的引用,当视图控制器实例化该自定义视图时,它必须设置该属性。

例如:

import UIKit

protocol CustomViewDelegate: class {         // make this class protocol so you can create `weak` reference
    func goToNextScene()
}

class CustomView: UIView {

    weak var delegate: CustomViewDelegate?   // make this `weak` to avoid strong reference cycle b/w view controller and its views

    @IBAction func toSecondButton(sender: AnyObject) {
        delegate?.goToNextScene() 
    }

}

然后

import UIKit

class ViewController: UIViewController, CustomViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let myCustomView = NSBundle.mainBundle().loadNibNamed("customView", owner: self, options: nil)[0] as! CustomView
        myCustomView.delegate = self

        // ... do whatever else you want with this custom view, adding it to your view hierarchy
    }


    func goToNextScene() {
        performSegueWithIdentifier("toSecond", sender: self)
    }

    ...

}