Search code examples
arraysswiftdictionaryuiviewflatmap

Swift: create a flat array of views from view hierarchy


I have a view hierarchy and I need to flatten it into a linear array, say:

+ rootView 0 - subView 1 - subview 2 + subview 3 - subview 3.1 - subview 3.2 - subview 4

I need an array of:

[0, 1, 2, 3, 3.1, 3.2, 4]

I wondered if map or flatMap can be used, or if I have to use the traditional way like a breadth-first traverse?

Thanks!


Solution

  • I would use a recursive function, which you can call on the 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)
    

    A slightly more abstract way of writing the above by putting it in an extension:

    extension UIView {
    
        func subviewsFlattened() -> [UIView] {
        
            var output: [UIView] = []
            output.append(self)
        
            for subview in self.subviews {
                output += subview.subviewsFlattened()
            }
        
            return output
        }
    
    }
    

    And then you can call it on any view:

    let allViews = someView.subviewsFlattened()