如何从xib调用performSegueWithIdentifier?
我有viewController与segue secondViewController名为“toSecond”。 在viewController我加载customView.xib
let myCustomView = NSBundle.mainBundle().loadNibNamed("customView", owner: self, options: nil)[0]
在这个customView我有button的行动:
viewController().goToSecond()
在viewController我有这个代码的function
func goToSecond() { self.performSegueWithIdentifier("toSecond", sender: self) }
但是当我按下customView中的button,我成为一个错误:
viewController没有标识符“toSecond”
当我直接从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()
没有引用加载你的自定义视图的视图控制器。 它正在实例化该类的第二个孤立实例(未连接到任何故事板),因此无法find该segue。
如果你真的UIView
这个自定义的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) } ... }