【发布时间】:2016-04-05 03:58:09
【问题描述】:
【问题讨论】:
-
“UIView 为空”怎么回事?
-
如果您需要检查视图是否有子视图,您的代码设计可能还有其他核心问题。为什么你不确定通过另一种方式发生了什么?例如,设置的配置或控制它的类?或者,一个 IBOutlet?
标签: ios swift uiview uibutton swift2
【问题讨论】:
标签: ios swift uiview uibutton swift2
您可以检查该特定视图中的子视图数量:
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.
}
}
【讨论】:
试试这个:
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
}
【讨论】:
UIView 有一个属性 subViews。这将返回一个包含所有子视图的数组。如果数组为空或计数为零,则其中没有子视图。
【讨论】:
我认为根据您的要求,您需要检查是否有任何按钮可以尝试
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
}
【讨论】:
好像您正在检查 UINavigationBar,
for (UIView *view in self.navigationController.navigationBar.subviews) {
if(view)
//Do your thing
}
【讨论】: