繁体   English   中英

使用 Swift 检查子视图是否在视图中

[英]Check if a subview is in a view using Swift

如何测试子视图是否已添加到父视图? 如果还没有添加,我想添加它。 否则,我想删除它。

您可以使用UIView方法isDescendantOfView

if mySubview.isDescendant(of: someParentView) {
    mySubview.removeFromSuperview()
} else {
    someParentView.addSubview(mySubview)
}

根据您的实现,您可能还需要使用if mySubview != nil包围所有内容。

这是一种更简洁的方法:

if myView != nil { // Make sure the view exists

        if self.view.subviews.contains(myView) {
            self.myView.removeFromSuperview() // Remove it
        } else {
           // Do Nothing
        }
    }
}
for view in self.view.subviews {
    if let subView = view as? YourNameView {
        subView.removeFromSuperview()
        break
    }
}

这里我们使用了两种不同的视图。 父视图是我们在其中搜索后代视图并检查是否添加到父视图的视图。

if parentView.subviews.contains(descendantView) {
   // descendant view added to the parent view.
  }else{
   // descendant view not added to the parent view.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM