Last active
November 3, 2023 13:37
-
-
Save noppefoxwolf/2adabfe82d05fe43e8bdf5af0b86356f to your computer and use it in GitHub Desktop.
UIScrollView+headerLayoutGuide
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 UIScrollView { | |
fileprivate var layoutGuideID: String { #function } | |
public var headerLayoutGuide: UILayoutGuide { | |
if let layoutGuide = addedHeaderLayoutGuide() { | |
return layoutGuide | |
} | |
// workaround: UIScrollView can't add new layoutGuide directly. | |
let anchorView = UIView() | |
addSubview(anchorView) | |
let newLayoutGuide = UILayoutGuide() | |
newLayoutGuide.identifier = layoutGuideID | |
anchorView.addLayoutGuide(newLayoutGuide) | |
let topConstraint = newLayoutGuide.topAnchor.constraint( | |
equalTo: frameLayoutGuide.topAnchor | |
) | |
topConstraint.priority = .defaultLow | |
NSLayoutConstraint.activate([ | |
topConstraint, | |
newLayoutGuide.leadingAnchor.constraint( | |
equalTo: leadingAnchor | |
), | |
newLayoutGuide.trailingAnchor.constraint( | |
equalTo: trailingAnchor | |
), | |
newLayoutGuide.bottomAnchor.constraint( | |
equalTo: topAnchor | |
), | |
]) | |
return newLayoutGuide | |
} | |
fileprivate func addedHeaderLayoutGuide() -> UILayoutGuide? { | |
layoutGuides.first(where: { $0.identifier == layoutGuideID }) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment