ios 使用 Swift 检查子视图是否在视图中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30937342/
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
Check if a subview is in a view using Swift
提问by Suragch
How do I test if a subview has already been added to a parent view? If it hasn't been added, I want to add it. Otherwise, I want to remove it.
如何测试子视图是否已添加到父视图?如果还没有添加,我想添加它。否则,我想删除它。
回答by Suragch
You can use the UIView
method isDescendantOfView
:
您可以使用以下UIView
方法isDescendantOfView
:
if mySubview.isDescendantOfView(someParentView) {
someParentView.mySubview.removeFromSuperview()
} else {
someParentView.addSubview(mySubview)
}
You may also need to surround everything with if mySubview != nil
depending on your implementation.
您可能还需要if mySubview != nil
根据您的实现来包围所有内容。
回答by Ryan Cocuzzo
This is a much cleaner way to do it:
这是一种更简洁的方法:
if myView != nil { // Make sure the view exists
if self.view.subviews.contains(myView) {
self.myView.removeFromSuperview() // Remove it
} else {
// Do Nothing
}
}
}
回答by Giang
for view in self.view.subviews {
if let subView = view as? YourNameView {
subView.removeFromSuperview()
break
}
}
回答by shubham
Here we used two different views. Parent view is the view in which we are searching for descendant view and check wether added to parent view or not.
这里我们使用了两种不同的视图。父视图是我们在其中搜索后代视图并检查是否添加到父视图的视图。
if parentView.subviews.contains(descendantView) {
// descendant view added to the parent view.
}else{
// descendant view not added to the parent view.
}