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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11889243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 19:39:59  来源:igfitidea点击:

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

iphoneobjective-ciosuikit

提问by Max

I was thinking maybe something like this might work:

我在想也许这样的事情可能会奏效:

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

I want to remove every kind of subview. UIImages, Buttons, Textfields etc.

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

回答by Max

[self.view.subviews makeObjectsPerformSelector: @selector(removeFromSuperview)];

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

它与您的变体相同,但略短。

回答by lcl

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

Identical version in Swift.

Swift 中的相同版本。

回答by mixel

Swift:

迅速:

//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()
}

回答by spikee

You can use like this

你可以这样使用

extension UIView {
    func removeAllSubviews() {
        subviews.forEach { ##代码##.removeFromSuperview() }
    }
}

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

view 是您要从中删除所有内容的视图。您只是通过执行 forEach 删除每个子视图

回答by ishwardgret

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

对于 Swift 4+。您可以扩展到UIView. 必要时调用它。

##代码##