What is the best way to remove all subviews from you self.view?

前端 未结 5 553
孤城傲影
孤城傲影 2020-12-12 12:07

I was thinking maybe something like this might work:

    for (UIView* b in self.view.subviews)
    {
       [b removeFromSuperview];
    }

相关标签:
5条回答
  • 2020-12-12 12:50

    Swift:

    extension UIView {
        func removeAllSubviews() {
            for subview in subviews {
                subview.removeFromSuperview()
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-12 12:53
    [self.view.subviews makeObjectsPerformSelector: @selector(removeFromSuperview)];
    

    It's identical to your variant, but slightly shorter.

    0 讨论(0)
  • 2020-12-12 13:04

    You can use like this

    //adding an object to the view
    view.addSubView(UIButton())
    
    // you can remove any UIControls you have added with this code
    view.subviews.forEach { (item) in
         item.removeFromSuperview()
    }
    

    view is the view that you want to remove everything from. you are just removing every subview by doing forEach

    0 讨论(0)
  • 2020-12-12 13:09

    For Swift 4+.You can make a extension to UIView. Call it whenever necessary.

    extension UIView {
        func removeAllSubviews() {
            subviews.forEach { $0.removeFromSuperview() }
        }
    }
    
    0 讨论(0)
  • 2020-12-12 13:12
    self.view.subviews.forEach({ $0.removeFromSuperview() })
    

    Identical version in Swift.

    0 讨论(0)
提交回复
热议问题