UIStackView : Is it really necessary to call both removeFromSuperView and removeArrangedSubview to remove a subview?

后端 未结 8 780
遥遥无期
遥遥无期 2021-02-02 05:04

From the UIStackView Class Reference

In removeArrangedSubview:

To prevent the view from appearing on screen after calling the stack’s removeArrang

相关标签:
8条回答
  • 2021-02-02 05:26

    I will suggest get arranged subviews then remove it like below code .

    for view in self.stackView.arrangedSubviews{
          self.stackView.removeArrangedSubview(view)
          view.removeFromSuperview()
    }
    
    0 讨论(0)
  • 2021-02-02 05:28

    Hacking With Swift provides a pretty good example and explanation, using Web views in this case.

    The reason is that you can remove something from a stack view's arranged subview list then re-add it later, without having to recreate it each time – it was hidden, not destroyed. We don't want a memory leak, so we want to remove deleted web views entirely. If you find your memory usage ballooning, you probably forgot this step!

    https://www.hackingwithswift.com/read/31/4/removing-views-from-a-uistackview-with-removearrangedsubview

    0 讨论(0)
  • 2021-02-02 05:29

    No, To remove specific view.

    func removeArrangedSubview(_ view: UIView)

    To remove all subviews

    stackView.arrangedSubviews.forEach { $0.removeFromSuperview() }

    0 讨论(0)
  • 2021-02-02 05:30

    To remove a arrangedSubview from a stackview is

    // To remove it from the view hierarchy
       subView.removeFromSuperview()
    
    0 讨论(0)
  • 2021-02-02 05:39

    For removing i use this extension. Don't really know is it necessary to remove constraints. But maybe it would help.

    extension UIStackView {
        func removeAllArrangedSubviews() {
            let removedSubviews = arrangedSubviews.reduce([]) { (allSubviews, subview) -> [UIView] in
                self.removeArrangedSubview(subview)
                return allSubviews + [subview]
            }
    
            for v in removedSubviews {
                if v.superview != nil {
                    NSLayoutConstraint.deactivate(v.constraints)
                    v.removeFromSuperview()
                }
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-02 05:42

    No, just call subview.removeFromSuperview()

    /* Removes a subview from the list of arranged subviews without removing it as
     a subview of the receiver.
        To remove the view as a subview, send it -removeFromSuperview as usual;
     the relevant UIStackView will remove it from its arrangedSubviews list
     automatically.
     */
    open func removeArrangedSubview(_ view: UIView)
    
    0 讨论(0)
提交回复
热议问题