Skip to content

Instantly share code, notes, and snippets.

@noppefoxwolf
Last active November 3, 2023 13:37
Show Gist options
  • Save noppefoxwolf/2adabfe82d05fe43e8bdf5af0b86356f to your computer and use it in GitHub Desktop.
Save noppefoxwolf/2adabfe82d05fe43e8bdf5af0b86356f to your computer and use it in GitHub Desktop.
UIScrollView+headerLayoutGuide
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