【问题标题】:How to check UIView is empty or not如何检查 UIView 是否为空
【发布时间】:2016-04-05 03:58:09
【问题描述】:

我有多个 UIView,然后在最后想要检查 UIView 上的添加和删除按钮后,我的视图是否为空。

上图第三个视图是空的如何以编程方式检查 此视图是否为空。

【问题讨论】:

  • “UIView 为空”怎么回事?
  • 如果您需要检查视图是否有子视图,您的代码设计可能还有其他核心问题。为什么你不确定通过另一种方式发生了什么?例如,设置的配置或控制它的类?或者,一个 IBOutlet?

标签: ios swift uiview uibutton swift2


【解决方案1】:

您可以检查该特定视图中的子视图数量:

if([theView.subviews count] == 0) {
    // View does not contain subviews
}

如果您在父视图中有多个 UIView,并且您希望找出哪些视图是空的,则循环遍历父子视图并检查每个子视图是否为空:

for(UIView * view in parentView.subviews) {
    if([view isKindOfClass:[UIView class]] && [view.subviews count] == 0) {
        // We found an empty UIView... 
        // Can you identify this view?
        // If you need to do something with it, do it here.
    }
}

【讨论】:

    【解决方案2】:

    试试这个:

    extension UIView {
        var isViewEmpty : Bool {
            return  self.subviews.count == 0 ;
        }
    }
    

    将扩展代码粘贴到 viewController 类之外。

    从视图中移除按钮后,每次检查isViewEmpty,如下所示,

    //if you don't have the object of view, you can get view as below,
    let view = bottonToRemove.superview;//this will give you obejct for check
    
    //your code to remove button from the view
    
    if view.isViewEmpty {
         //implement your logic for if view is empty
    }else{
        //view not empty
        //do you stuff
    }
    

    【讨论】:

      【解决方案3】:

      UIView 有一个属性 subViews。这将返回一个包含所有子视图的数组。如果数组为空或计数为零,则其中没有子视图。

      【讨论】:

        【解决方案4】:

        我认为根据您的要求,您需要检查是否有任何按钮可以尝试

        BOOL isEmpty = true;
        for (UIButton *btn in viewTest.subviews) {
            if ([btn isKindOfClass:[UIButton class]]) {
                isEmpty = false;
                break;
            }
        }
        if (isEmpty == false) {
            // there is button in view
        }
        else
        {
        // there no button in view
        }
        

        【讨论】:

          【解决方案5】:

          好像您正在检查 UINavigationBar,

          for (UIView *view in self.navigationController.navigationBar.subviews) {
          
          if(view)
            //Do your thing
          }
          

          【讨论】:

          • 请在否决答案之前分享您的不满和疑虑。
          • 请将 UINavigationbar 更改为 UIView 对象,它应该是您的 UIView 的对象。正如 Iqbal 所说的 UIView。
          • @ShaluRaj - 同意 HarshIT 的评论。根据问题,这与没有子视图的视图和导航栏的子视图无关。
          猜你喜欢
          • 2015-10-12
          • 2017-11-15
          • 2020-05-29
          • 2018-04-02
          • 2018-01-08
          • 2020-09-25
          • 2012-01-15
          • 2016-07-16
          • 2021-08-14
          相关资源
          最近更新 更多