当视图消失时,我会从superview中删除此collectionview,因为内存问题,但我想在视图出现时添加回来,我只想将其添加回去!还是有其他办法吗?感谢。
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
let subViews = self.view.subviews
for subview in subViews{
if subview.tag == 1 {
subview.removeFromSuperview()
}
}
}
更新
var savedView: UIView?
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
let subViews = self.view.subviews
for subview in subViews{
if subview.tag == 1 {
savedView = subview
subview.removeFromSuperview()
}
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let subview = savedView {
view.addSubview(subview)
savedView = nil
}
}
但它没有添加回来。
答案 0 :(得分:1)
在视图控制器中创建可选属性。在viewDidDisappear
方法中将找到的子视图分配给此可选属性。然后在viewWillAppear
方法中,您可以检查是否设置了可选属性。如果设置,请将其添加回子视图。
添加此属性:
var savedView: UIView?
然后在viewDidDisappear
:
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// This assumes there is no other deep subview with a tag of 1
// If this isn't true, use your current for-loop to find the subview
if let subview = subviews.viewWithTag(1) {
savedView = subview
subview.removeFromSuperview
}
}
在viewWillAppear
中执行此操作:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let subview = savedView {
addSubview(savedView)
savedView = nil
}
}