Skip to content

Instantly share code, notes, and snippets.

@Chronos2500
Last active January 2, 2026 16:08
Show Gist options
  • Select an option

  • Save Chronos2500/b53ef61d8d8769f364f4cb61351dc549 to your computer and use it in GitHub Desktop.

Select an option

Save Chronos2500/b53ef61d8d8769f364f4cb61351dc549 to your computer and use it in GitHub Desktop.
import SwiftUI
struct CustomScrollTargetBehavior: ScrollTargetBehavior {
func properties(context: PropertiesContext) -> Properties {
var properties = ScrollTargetBehaviorProperties.init()
properties.limitsScrolls = false
return properties
}
func updateTarget(_ target: inout ScrollTarget, context: TargetContext) {
// Temporary value
let componentRect = CGRect(x: 0, y: 0, width: 200, height: 400)
let targetMinY = target.rect.minY
let snapY = targetMinY <= componentRect.midY
? componentRect.minY
: componentRect.maxY
if componentRect.minY <= targetMinY, targetMinY <= componentRect.maxY {
target.rect.origin.y = snapY
}
}
}
#Preview {
NavigationStack {
ScrollView {
LazyVStack {
Color.yellow
.frame(height: 400)
ForEach(0..<100) { index in
Text("Item \(index)")
.padding(.vertical)
.frame(maxWidth: .infinity)
}
}
}
.scrollTargetBehavior(CustomScrollTargetBehavior())
.navigationTitle("Custom Scroll Target")
.navigationBarTitleDisplayMode(.inline)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment