[英]How to access the child view controller from parent view controller in swift?
I have a view controller which has a child view controller and I want to access that child view controller from its parent view controller.我有一个视图控制器,它有一个子视图控制器,我想从它的父视图控制器访问该子视图控制器。
How can I achieve that?我怎样才能做到这一点?
The answer is ... (drum-roll......) ... it depends.. :-)答案是......(鼓声......)......这取决于...... :-)
NSViewController
& UIViewController
have a .parent
property. NSViewController
和UIViewController
有一个.parent
属性。 https://developer.apple.com/documentation/uikit/uiviewcontroller/1621362-parent https://developer.apple.com/documentation/appkit/nsviewcontroller/1434491-parent https://developer.apple.com/documentation/uikit/uiviewcontroller/1621362-parent https://developer.apple.com/documentation/appkit/nsviewcontroller/1434491-parent
However, it is only populated if you're implementing the container-view-controller design pattern: https://developer.apple.com/library/archive/featuredarticles/ViewControllerPGforiPhoneOS/ImplementingaContainerViewController.html (many uikit components use this pattern) IE:但是,只有在实现容器-视图-控制器设计模式时才会填充它: https : //developer.apple.com/library/archive/featuredarticles/ViewControllerPGforiPhoneOS/ImplementingaContainerViewController.html (许多 uikit 组件使用此模式)IE :
aViewController.addChild(bViewController)
bViewControler.didMove(toParent: aViewController)
bViewController.parent // is aViewController
* Note: you'll have to manage the view stack yourself, this just ensures things like the lifecycle/drawing/resize/etc handlers happen in the correct order *注意:你必须自己管理视图堆栈,这只是确保生命周期/绘图/调整大小/等处理程序以正确的顺序发生
If you need to retain a reference to a view controller (child or otherwise), create a property on the child and set a reference to it, or use the container-view-controller design, it's very useful.如果您需要保留对视图控制器(子级或其他)的引用,在子级上创建属性并设置对它的引用,或者使用容器-视图-控制器设计,这非常有用。
Cheers干杯
- J - J
There are many ways but for simply explanation I think this example will be instructive for you.有很多方法,但为了简单的解释,我认为这个例子会对你有所启发。
Suppose that you are trying to achieve navigate your viewcontrollers and using navigation controller for that in a stack假设您正在尝试实现导航视图控制器并在堆栈中使用导航控制器
let parentVC = UIViewController()
let childVC = UIViewController()
parentVC.navigationController?.viewControllers.append(childVC)
let childVCisHere = parentVC.navigationController?.viewControllers.first
Finally think about the analogy I established on - GodFather - family hieararchy最后想想我建立的类比- 教父 -家族等级制度
Don Vito Corleone , he is the boss also father of the family parentVC唐·维托·柯里昂,他是老板也是父亲的家族parentVC的
Sonny Corleone , he is dealing with dirty jobs, navigate childs behalf of family navigationController桑尼柯里昂,他正在处理肮脏的工作,家庭navigationController的导航孩子的名义
Michael Corleone , he is little bro, people see him on the screen mostly :) childVC Michael Corleone ,他是小兄弟,人们大多在屏幕上看到他:) childVC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.