从你的 self. view 中删除所有子视图的最好方法是什么?

我在想也许这样可以行得通:

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

我想删除每一种子视图。 UIImages,按钮,文本字段等。

46308 次浏览
[self.view.subviews makeObjectsPerformSelector: @selector(removeFromSuperview)];

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

Swift:

extension UIView {
func removeAllSubviews() {
for subview in subviews {
subview.removeFromSuperview()
}
}
}
self.view.subviews.forEach({ $0.removeFromSuperview() })

Identical version in Swift.

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

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

extension UIView {
func removeAllSubviews() {
subviews.forEach { $0.removeFromSuperview() }
}
}