Skip to content

Instantly share code, notes, and snippets.

@madson
Created October 5, 2017 13:44
Show Gist options
  • Save madson/2a46ef208e3a0057491b9c18e46188ed to your computer and use it in GitHub Desktop.
Save madson/2a46ef208e3a0057491b9c18e46188ed to your computer and use it in GitHub Desktop.
import Foundation
import UIKit
extension UIView {
var allSubviews: [UIView] {
get {
var viewsFound: [UIView] = [UIView]()
return viewsFound
}
}
convenience init(subviews: [UIView]) {
self.init()
subviews.forEach{ self.addSubview($0) }
}
convenience init(backgroundColor: UIColor) {
self.init()
self.backgroundColor = backgroundColor
}
func coloredSubviews(color: UIColor) -> [UIView] {
var viewsFound: [UIView] = [UIView]()
return viewsFound
}
}
let view = UIView(subviews: [UIView(backgroundColor: .yellow),
UIView(backgroundColor: .red),
UIView(backgroundColor: .yellow),
UIView(subviews: [
UIView(backgroundColor: .red),
UIView(backgroundColor: .red),
UIView(backgroundColor: .white),
UIView(subviews: [
UIView(backgroundColor: .red),
UIView(backgroundColor: .yellow),
UIView(backgroundColor: .white),
UIView(subviews: [
UIView(backgroundColor: .white),
UIView(backgroundColor: .red),
UIView(backgroundColor: .red),
UIView(subviews: [
UIView(backgroundColor: .white),
UIView(backgroundColor: .red),
UIView(backgroundColor: .red)
])
])
]),
UIView(subviews: [
UIView(backgroundColor: .red),
UIView(backgroundColor: .red),
UIView(backgroundColor: .yellow)
]),
UIView(backgroundColor: .yellow),
UIView(backgroundColor: .red),
])])
let redViews = view.coloredSubviews(color: .red)
let yellowViews = view.coloredSubviews(color: .yellow)
let allSubviews = view.allSubviews
print(redViews.count) // should be 11
print(yellowViews.count) // should be 5
print(allSubviews.count) // should be 25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment