Skip to content

Instantly share code, notes, and snippets.

@jakehawken
Last active June 26, 2023 15:14
Show Gist options
  • Save jakehawken/4d3e30463a597a4b4b930c9140efbc31 to your computer and use it in GitHub Desktop.
Save jakehawken/4d3e30463a597a4b4b930c9140efbc31 to your computer and use it in GitHub Desktop.
Some handy methods for view debugging in iOS.
extension UIView {
func firstSuperview<T: UIView>(ofType type: T.Type) -> T? {
guard let superview = superview else {
return nil
}
if let superViewAsT = superview as? T {
return superViewAsT
}
return superview.firstSuperview(ofType: type)
}
func firstSubview<T: UIView>(ofType type: T.Type) -> T? {
guard subviews.isEmpty == false else {
return nil
}
if let firstOfType = subviews.first(where: { $0 is T }) as? T {
return firstOfType
}
for view in subviews {
if let subviewOfType = view.firstSubview(ofType: type) {
return subviewOfType
}
}
return nil
}
func allSubviews<T: UIView>(ofType type: T.Type, isRecursive: Bool = true) -> [T] {
var tViews = subviews.compactMap { $0 as? T }
if isRecursive {
subviews.forEach { tViews += $0.allSubviews(ofType: type) }
}
return tViews
}
func forEachSubview(isRecursive: Bool, doBlock: (UIView)->()) {
subviews.forEach { (subview) in
doBlock(subview)
if isRecursive {
subview.forEachSubview(isRecursive: isRecursive, doBlock: doBlock)
}
}
}
}
@jakehawken
Copy link
Author

Check it out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment