我已经阅读了关于这个主题的所有其他帖子,但它们似乎对我没有帮助。
我有一个启动两个选项卡的 UITabBarController。我想将 tab1 中收集的数据传递给 UITabBar ViewController。我正在尝试为此使用 delegete 协议(protocol),但我无法在发送 ViewController 中设置委托(delegate)变量。永远不会调用 prepare for segue。我什至无法循环浏览 Tabbar Controller 的 ViewDidLoad() 内选项卡的 View Controller ,因为它们尚未创建,因此为零。
我以前使用过委托(delegate),它看起来相当简单。我在 Tabbar 中使用它重要吗?
当我运行代码时,会调用 TabBarViewController 中的 viewDidLoad() 但不会调用 preparefor segue。
调用了 MeViewController 中的 IBAction donePressed,但未调用委托(delegate),因为它未设置。
这是代码——
protocol DetailsDelegate: class {
func myDetailsGathered( myDetails: MyDetails )
}
/// RECEIVING VIEW CONTROLLER
class TabBarViewController: UITabBarController, DetailsDelegate
{
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
print("prepare for segue called\n");
if let destinationViewController = segue.destination as? MeViewController
{
destinationViewController.delegate = self
}
}
override func viewDidLoad()
{
print("ViewDidLoad Called \n")
}
func myDetailsGathered(myDetails: MyDetails)
{
self.myDetails = myDetails
print("My details gathered \n")
}
}
---------------
/// SENDING VIEW CONTROLLER
class MeViewController: UIViewController
{
weak var delegate: DetailsDelegate?
override func viewDidLoad()
{
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
// I have UIButton in the view and this is invoked when its pressed.
@IBAction func donePressed(_ sender: Any)
{
var infoToPass = MyDetails()
print("looks like we are done")
delegate?.myDetailsGathered(infoToPass: myDetails)
}
}
最佳答案
prepareForSegue
在您执行转场时被调用。你不这样做,这就是它不会被调用的原因。
A segue defines a transition between two view controllers in your app’s storyboard file.
您应该使用单例
类来存储变量并在不同的 Controller 之间访问它们。你这样声明一个:
class Singleton {
static let sharedInstance = Singleton()
var name = ""
}
分配给单例:
Singleton.sharedInstance.name = "Some name"
从任何 Controller 读取它:
let name = Singleton.sharedInstance.name
关于ios - 准备在 UITabbarController 中不调用 segue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46877330/