Last active
June 26, 2023 15:14
-
-
Save jakehawken/4d3e30463a597a4b4b930c9140efbc31 to your computer and use it in GitHub Desktop.
Some handy methods for view debugging in iOS.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Check it out.