[英]Swift - Loop through different object types
Current I do this to loop through all of my buttons:当前我这样做是为了遍历我的所有按钮:
for objects in view.subviews {
if let object = objects as? UIButton {
object.isEnabled = false
}
}
Can I also include UIView
and UILabel
in this loop?我还可以在这个循环中包含
UIView
和UILabel
吗?
So instead of only objects as? UIButton
所以而不是只有
objects as? UIButton
objects as? UIButton
, I want objects as? UIButton, UIView, UILabel
objects as? UIButton
,我想要objects as? UIButton, UIView, UILabel
objects as? UIButton, UIView, UILabel
. objects as? UIButton, UIView, UILabel
。
You could do it like this:你可以这样做:
for objects in view.subviews {
if let object = objects as? UIButton {
object.isEnabled = false
}
if let object = objects as? UIView {
object.isHidden = false
}
if let object = objects as? UILabel {
object.isEnabled = false
}
}
No, you can't set the isEnabled
property of labels and other UIViews
.不,您不能设置标签和其他
UIViews
的isEnabled
属性。 Only objects that inherit from UIControl
have the isEnabled
property.只有从
UIControl
继承的对象才具有isEnabled
属性。
I would advise against looping through all a view's subviews and disabling all the controls.我建议不要遍历所有视图的子视图并禁用所有控件。 It is a very "shotgun" approach, and fragile.
这是一种非常“霰弹枪”的方法,而且很脆弱。
A problem with it is that it won't work if you have any complexity to your view hierarchy.它的一个问题是,如果您的视图层次结构有任何复杂性,它将无法工作。 If you have buttons in a stack view, for example, your code would miss them.
例如,如果您在堆栈视图中有按钮,您的代码就会错过它们。 Or say they are in a table view.
或者说他们在表格视图中。 That won't work either.
那也行不通。
Instead, I would suggest putting the outlets of the controls you want to disable into an array in your viewDidLoad()
method.相反,我建议将要禁用的控件的出口放入
viewDidLoad()
方法中的数组中。 Then when you want to disable them all, loop through that array and set isEnabled
to false for each.然后,当您想全部禁用它们时,遍历该数组并将每个数组的
isEnabled
设置为 false。
An alternative is to assign tags to the relevant UI elements.另一种方法是为相关的 UI 元素分配标签。
In the loop (or forEach
closure) check if the tag is in the required range and conditional downcast the view to UIControl
在循环(或
forEach
闭包)中检查标签是否在所需的范围内,并有条件地将视图向下转换为UIControl
view.subviews.forEach{ subView in
guard (100...105).contains(subView.tag) else { return }
(subView as? UIControl)?.isEnabled = false
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.