Created
December 13, 2019 17:49
-
-
Save shaps80/d73b75e8ffa192bdf1a2ca08a510d015 to your computer and use it in GitHub Desktop.
A UIView helper extension that finds the 'key' view in the controller's hierarchy. Useful for finding a UITableView/UICollectionView or any other view that's NOT the controller's root view.
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
import UIKit | |
internal extension UIViewController { | |
/// Returns the 'key' view for this controller. I.e. the top-most visible view that covers the view's entire bounds. | |
/// This is generally the controller's root view, but it could also be a nested table/collection view, etc... | |
@objc var _keyView: UIView { | |
return view._keyViews(in: self).last ?? view | |
} | |
} | |
internal extension UIView { | |
/// Returns all potentional 'key' views in this controller | |
/// - Parameter controller: The controller to search | |
@objc func _keyViews(in controller: UIViewController) -> [UIView] { | |
let views = subviews.filter { $0._isKeyView(in: controller) } | |
return views + views.flatMap { $0._keyViews(in: controller) } | |
} | |
/// Returns true if this view is a 'key' in the specified controller | |
/// - Parameter controller: The controller to search | |
@objc func _isKeyView(in controller: UIViewController) -> Bool { | |
return alpha > 0 | |
&& !isHidden | |
&& isUserInteractionEnabled | |
&& (frame.size == controller.view.safeAreaLayoutGuide.layoutFrame.size | |
|| frame.size == controller.view.bounds.size) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment