我是swift的新手,我希望将数组从容器视图传递到父视图。我使用故事板创建了容器视图,但容器视图以编程方式显示和消失,如下所示:
//in parent view controller, inside viewDidLoad()
CameraView.isHidden = true
//in child view controller, on click of button,
let parent = self.parent as! DiaryEntryViewController
parent.CameraView.isHidden = true
每当我点击按钮显示容器视图时,我希望显示所选数据。 我不知道如何将值从子视图控制器传递到父视图控制器,我在哪里可以访问这些值。这些值需要在一个函数内访问,该函数在单击父视图控制器内的另一个按钮时调用。
答案 0 :(得分:4)
这样做的步骤。
你的容器视图必须包含一个嵌入到子视图控制器的segue,这个名称就像这样...... ...#34; homeToContainer" (见附图)
将此方法添加到父视图控制器(DiaryEntryViewController)
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? ChildViewController,
segue.identifier == "homeToContainer" {
vc.delegate = self
}
}
在ChildViewController中添加Protocol及其变量
protocol ChildToParentProtocol:class {
func buttonClickedByUser()
func needToPassInfoToParent(with value:Int)
}
class ChildViewController: UIViewController {
weak var delegate:ChildToParentProtocol? = nil
@IBAction func createTourPressed(_ sender: UIButton) {
// Call here delegate methods to tell parent about the action
delegate?.buttonClickedByUser()
}
}
在您的父ViewController的最后一个中,添加此扩展, 扩展DiaryEntryViewController:ChildToParentProtocol {
func buttonClickedByUser() {
}
func needToPassInfoToParent(with value:Int) {
}
}
答案 1 :(得分:0)
如果以编程方式添加了容器视图,则应使用回调将值从容器视图返回到父视图。
父控制器:
let containerView = UIView()
containerView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(containerView)
NSLayoutConstraint.activate([
containerView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0),
containerView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0),
containerView.topAnchor.constraint(equalTo: headerView.bottomAnchor, constant: 0),
containerView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0),
])
let controller = YourViewController(nibName: "YourNibView", bundle: nil)
//This is important to get value back and also define callback to container view call as well
controller.callback = { result in
self.isCardJoinedFromJoinScreen = true
self.viewWillAppear(true)
}
addChild(controller)
controller.view.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(controller.view)
NSLayoutConstraint.activate([
controller.view.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
controller.view.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
controller.view.topAnchor.constraint(equalTo: containerView.topAnchor),
controller.view.bottomAnchor.constraint(equalTo: containerView.bottomAnchor)
])
容器视图控制器
定义此回调
var callback : ((Bool)->())?
,然后在将值传递给父控制器时调用此回调,如
self.callback?(true) or self.callback?(false)