gpt4 book ai didi

swift - 从父 View 中删除 View

转载 作者:行者123 更新时间:2023-11-28 06:24:14 26 4
gpt4 key购买 nike

当 View 消失时,我从 super View 中删除了这个 Collection View ,因为内存问题,但我想在 View 出现时将其添加回来,我只想将它添加回来!或者还有另一种方法吗?谢谢。

  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
}
}

但它不会将其添加回来。

最佳答案

在您的 View Controller 中创建一个可选属性。在您的 viewDidDisappear 方法中将找到的 subview 分配给此可选属性。然后在 viewWillAppear 方法中,您可以检查是否设置了可选属性。如果已设置,则将其添加回 subview 。

添加此属性:

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
}
}

关于swift - 从父 View 中删除 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42470464/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com