如何在Swift中删除视图的所有子视图? [英] How to remove all subviews of a view in Swift?

查看:845
本文介绍了如何在Swift中删除视图的所有子视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种简单的方法,可以一次从超级视图中删除所有子视图,而不是一个一个地删除它们.

I'm looking for a simple method to remove at once all subviews from a superview instead of removing them one by one.

//I'm trying something like this, but is not working
let theSubviews : Array = container_view.subviews
for (view : NSView) in theSubviews {
    view.removeFromSuperview(container_view)
}

我想念什么?

更新

我的应用有一个主container_view.为了提供某种导航,我必须将其他视图添加为container_view的子视图.

My app has a main container_view. I have to add different other views as subviews to container_view in order to provide a sort of navigation.

因此,当单击按钮以打开"特定页面时,我需要删除所有子视图并添加新的子视图.

So, when clicking the button to "open" a particular page, I need to remove allsubviews and add the new one.

更新2-可行的解决方案(OS X)

我想苹果公司已经修复了它.

I guess Apple fixed it.

现在,它比以往更容易了,只需致电:

Now it is more easy than ever, just call:

for view in containerView.subviews{
    view.removeFromSuperview()
}

推荐答案

(感谢耶利米/罗洛)

到目前为止,在iOS的Swift中做到这一点的最佳方法是:

By far the best way to do this in Swift for iOS is:

view.subviews.forEach({ $0.removeFromSuperview() }) // this gets things done
view.subviews.map({ $0.removeFromSuperview() }) // this returns modified array

^^这些功能很有趣!

^^ These features are fun!

let funTimes = ["Awesome","Crazy","WTF"]
extension String { 
    func readIt() {
        print(self)
    }
}

funTimes.forEach({ $0.readIt() })

////结束编辑

只需执行以下操作:

for view in self.view.subviews {
    view.removeFromSuperview()
}

或者如果您正在寻找特定的班级

Or if you are looking for a specific class

for view:CustomViewClass! in self.view.subviews {
        if view.isKindOfClass(CustomViewClass) {
            view.doClassThing()
        }
    }

这篇关于如何在Swift中删除视图的所有子视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆