如何在 Swift 中删除视图的所有子视图? [英] How to remove all subviews of a view in 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)
我猜苹果修复了它.
现在比以往任何时候都容易,只需调用:
Now it is more easy than ever, just call:
for view in containerView.subviews{
view.removeFromSuperview()
}
推荐答案
(感谢 Jeremiah/Rollo)
(thanks Jeremiah / Rollo)
到目前为止,在 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屋!