将值从子视图页面快速传递到 Pageview 控制器
Posted
技术标签:
【中文标题】将值从子视图页面快速传递到 Pageview 控制器【英文标题】:Pass value from child view page to Pageview controller in swift 【发布时间】:2020-07-22 11:10:21 【问题描述】:我有一个pageView Controller 说A。它连接到三个子View Controller。我想从子视图控制器取回一个值回到根页面视图控制器。 在android中可以通过接口传递轻松完成,而在iOS中使用协议会遇到麻烦。
我就是这样的
protocol Z
func runZ()
Class A: UIViewController, Z
func runZ( withValue value: String)
//Perform some function
var orderedViewControllers: [UIViewController] =
var myViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "myViewController") as! MyViewController
myViewController.z = self
return [ myViewController,
UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "C")]
()
Class B : UIViewController
var z = A.self
func sendBackToA()
(z as! Z).runZ(withValue : "CustomString")
我在 myViewController.z = self 处收到错误 无法将类型 '(A) -> () -> A' 的值分配给类型 'A.Type'。
我通过这样的初始化使其以某种方式工作
myViewController.z = A.self
但我的应用程序崩溃了
无法将类型“A.Type”(0x1e0d854d8)的值转换为“Z”
【问题讨论】:
嘿,您已使用此链接的第三个答案***.com/questions/39285588/…。如果你的问题没有解决,请告诉我,我会在这个问题的帖子中写完整的代码。 【参考方案1】:protocol Z:class
func runZ(withValue value: String?)
class A: UIViewController, Z, UINavigationControllerDelegate
func runZ(withValue value: String?)
//Perform some function
var orderedViewControllers: [UIViewController] =
var myViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "B") as! B
myViewController.z = self
return [ myViewController,
UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "C")]
()
class B : UIViewController
weak var z:Z?
func sendBackToA()
z?.runZ(withValue : "CustomString")
【讨论】:
【参考方案2】:一些事情......
protocol Z
func runZ(withValue value: String)
class A: UIViewController, Z // "class" rather than "Class"
func runZ( withValue value: String)
//Perform some function
func orderedViewControllers() -> [UIViewController] // func because variable declarations don't have a "self"
// Should get rid of the forced unwrap in the next line
let myViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "myViewController") as! B
myViewController.z = self
return [ myViewController, UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "C")]
class B : UIViewController // "class" rather than "Class"
var z: Z? // The other controller will do the initialization.
func sendBackToA()
// Verify that the delegate is registered
if let z = z
z.runZ(withValue : "CustomString")
else
print("Missing delegate assignment")
【讨论】:
以上是关于将值从子视图页面快速传递到 Pageview 控制器的主要内容,如果未能解决你的问题,请参考以下文章