如何从 xib 调用 performSegueWithIdentifier?

How to call performSegueWithIdentifier from xib?

我有 viewController segue 到名为 "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 has no segue with identifier 'toSecond'

当我直接从 viewController 调用此函数时一切正常!

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

自定义视图源代码:

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)
    }
...

}

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

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


例如:

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)
    }

    ...

}