繁体   English   中英

如何从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没有标识为“ 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)
    }
...

}

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

如果您真的要让此自定义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)
    }

    ...

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM