【问题标题】:How to call performSegueWithIdentifier from xib?如何从 xib 调用 performSegueWithIdentifier?
【发布时间】:2016-07-05 20:45:09
【问题描述】:

我有 viewController 与名为“toSecond”的 secondViewController 的 segue。 在 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)
    }
...

}

【问题讨论】:

  • 如果自定义视图的文件所有者是视图控制器,我不明白这段代码:viewController().goToSecond() 是如何包含在自定义视图中的。您能否为您的自定义视图提供更多源代码?您如何在自定义视图中创建对视图控制器的引用?
  • 我在展示viewController中展示了customView...我在viewController和secondViewController之间的segue...我可以直接从viewController调用func goToSecond(),但不能从customView调用!如果在函数 goToSecond 中写一些类似 print("Click!") 我在日志中看到这个点击!
  • 以后,我鼓励你坚持使用Cocoa naming conventions,所有类名都以大写字母开头。这是不必要的混乱......

标签: ios swift view segue xib


【解决方案1】:

问题是您的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)
    }

    ...

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    • 2011-07-20
    • 2013-11-04
    相关资源
    最近更新 更多