获取 ViewController 内的所有视图

Ila*_*tal 3 view uiviewcontroller ios swift

我正在尝试获取 UIViewController 中的所有视图。

我正在使用这段代码:

    for subview : UIView in self.view.subviews{
        //code here
    }
Run Code Online (Sandbox Code Playgroud)

the problem is that I don't get views that are inside a UIView. so I get all view except of their children.

please, how can I get ALL Views that are either child or parent inside my UIViewController? even if a view has a child that has a child that has a child. I want to go through all views.

thanx in advance :)

(please in swift 4.0)

rma*_*ddy 5

您需要递归处理所有子视图。

func processSubviews(of view: UIView) {
    // 1. code here do something with view
    for subview in view.subviews {
        // 2. code here do something with subview
        processSubviews(of: subview)
        // 3. code here do something with subview
    }
    // 4. code here do something with view
}
Run Code Online (Sandbox Code Playgroud)

您需要将代码放在位置 1、2、3 或 4(或者可能是其中两个或更多位置),具体取决于您想要的结果。

然后你可以将其称为:

processSubviews(of: self.view)
Run Code Online (Sandbox Code Playgroud)