我正在尝试将数据传递到容器视图,该视图将包含多个子视图控制器中的任何一个,具体取决于用户状态。我在第一次实例化新VC时成功传递数据,但如果我关闭并重新打开该子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))
}
最后摆脱孩子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()
}
})
}
非常感谢任何见解,谢谢!
答案 0 :(得分:1)
我发现您的代码存在问题。在func onMapButtonPressed(sender: UIButton)
中,您假设该位置始终为0.它首次起作用,因为它在那里。但是在第一次删除它并在bringInSubview(name:String)
中重新添加后,位置会发生变化。你应该检查一下。
希望这有帮助!