我将使用递归函数,您可以在
rootView
。
func flattenSubviews(view: UIView) -> [UIView] {
var flatArray: [UIView] = []
flatArray.append(view)
for subview in view.subviews {
flatArray += flattenSubviews(view: subview)
}
return flatArray
}
。
let flattenedViews = flattenSubviews(view: rootView)
通过将其放在扩展中来编写上述内容的一种略为抽象的方式:
extension UIView {
func subviewsFlattened() -> [UIView] {
var output: [UIView] = []
output.append(self)
for subview in self.subviews {
output += subview.subviewsFlattened()
}
return output
}
}
然后您可以在任何视图上调用它:
let allViews = someView.subviewsFlattened()