By doing . copy(), I could perform the removal of each subview while mutating the self. subviews array. This is because the copied array (subViews) contains all of the references to the objects and is not mutated.
If you need a quick way to get hold of a view inside a complicated view hierarchy, you're looking for viewWithTag() – give it the tag to find and a view to search from, and this method will search all subviews, and all sub-subviews, and so on, until it finds a view with the matching tag number.
[self.view.subviews makeObjectsPerformSelector: @selector(removeFromSuperview)];
It's identical to your variant, but slightly shorter.
self.view.subviews.forEach({ $0.removeFromSuperview() })
Identical version in Swift.
Swift:
extension UIView {
func removeAllSubviews() {
for subview in subviews {
subview.removeFromSuperview()
}
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With