【问题标题】:Remove view from superview从超级视图中删除视图
【发布时间】:2017-02-26 15:33:06
【问题描述】:

当视图消失时,我从超级视图中删除了这个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
    }
}

但它不会将其添加回来。

【问题讨论】:

  • 您确定该子视图的标记为 1,并且该子视图正在被适当地删除,并且 saveView 在保存后不是 nil 吗?
  • 是的,collectionview 已被删除,但我无法将其添加回来。当我 print() 视图中的子视图确实消失时,collectionview 被保存。
  • 这是UICollectionViewController吗?
  • 不,不是。如果我从代码创建collectionview,它会起作用吗?我可以在 viewWillAppear 中创建它并在 viewWillDisappear 中删除它。

标签: swift swift3 uicollectionview


【解决方案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
   }
}

【讨论】:

  • 感谢@rmaddy,但它不起作用。我只是更新我的问题。您还有其他建议吗?谢谢
  • 你没有像我在回答中那样声明savedView
  • 对不起,我只是更新了问题。但是还是不行
  • 子视图被移除保存成功,但是放不回去。
  • addSubview 的呼叫是否已到达?如果是,但集合视图似乎没有出现,请在添加回来后尝试重新加载集合视图。
猜你喜欢
  • 1970-01-01
  • 2012-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多