在容器视图中,数据仅传递给 child VC 一次

Data is passed only once to child VC in container view

我正在尝试将数据传递到容器视图,该视图将根据用户状态包含多个 child 视图控制器中的任何一个。我在第一次实例化新 VC 时成功传递了数据,但是如果我关闭并重新打开 child VC,数据就不会再次传递。这是按下按钮时的动作:

@IBAction func onMapButtonPressed(sender: UIButton) {
      let latitude = Double(selectedPlace.latitude!)
      let longitude = Double(selectedPlace.longitude!)
      bringInSubview("mapViewScreen")
      (childViewControllers[0] as! PlaceMapDetailVC).latitude = latitude!
      (childViewControllers[0] as! PlaceMapDetailVC).longitude = longitude!
      (childViewControllers[0] as! PlaceMapDetailVC).placeName = selectedPlace["name"] as! String
   }

以及辅助方法:

func bringInSubview(name:String) {

      newViewController = self.storyboard?.instantiateViewControllerWithIdentifier(name)
      newViewController!.view.translatesAutoresizingMaskIntoConstraints = false
      self.addChildViewController(self.newViewController!)
      self.addSubview(self.newViewController!.view, toView: self.containerView)
      view.bringSubviewToFront(containerView)
      view.bringSubviewToFront(closeSubviewButton)

      UIView.animateWithDuration(0.3, animations: {
         self.containerView.alpha = 1
         }, completion: { finished in
            // anything else needed in completion block?
      })
   }

func addSubview(subView:UIView, toView parentView:UIView) {
      parentView.addSubview(subView)
      var viewBindingsDict = [String: AnyObject]()
      viewBindingsDict["subView"] = subView
    parentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[subView]|",
         options: [], metrics: nil, views: viewBindingsDict))
      parentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[subView]|",
         options: [], metrics: nil, views: viewBindingsDict))
   }

终于摆脱了 child VC:

@IBAction func onCloseButtonInSubviewPressed(sender: UIButton) {
      UIView.animateWithDuration(0.3, animations: {
         self.containerView.alpha = 0
         self.view.sendSubviewToBack(self.closeSubviewButton)
         },
         completion: { finished in
            self.view.sendSubviewToBack(self.containerView)

            // clears out prior view that was there to free up memory
            for view in self.containerView.subviews {
               view.removeFromSuperview()
            }
      })
   }

非常感谢任何见解,谢谢!!!

我发现你的代码有问题。在 func onMapButtonPressed(sender: UIButton) 中,您假设位置始终为 0。它在第一时间起作用,因为它在那里。但是在你第一次删除它并在 bringInSubview(name:String) 中再次 re-add 后,位置发生了变化。你应该检查一下。

希望对您有所帮助!