Skip to content

Instantly share code, notes, and snippets.

@felix-larsen
Created March 16, 2021 19:20
Show Gist options
  • Save felix-larsen/8a78ae710f3b66d0dc309129bb170bc5 to your computer and use it in GitHub Desktop.
Save felix-larsen/8a78ae710f3b66d0dc309129bb170bc5 to your computer and use it in GitHub Desktop.
Disappearing Floating action button SwiftUI
import SwiftUI
import Combine
struct ContentView: View {
@State var showFab = true
@State var scrollOffset: CGFloat = 0.00
var body: some View {
ScrollView {
VStack (alignment: .leading) {
ForEach(0..<30) { i in
HStack {
Text("Item \(i)").padding()
Spacer()
}
}
}.background(GeometryReader {
return Color.clear.preference(key: ViewOffsetKey.self,
value: -$0.frame(in: .named("scroll")).origin.y)
})
.onPreferenceChange(ViewOffsetKey.self) { offset in
withAnimation {
if offset > 50 {
showFab = offset < scrollOffset
} else {
showFab = true
}
}
scrollOffset = offset
}
}
.coordinateSpace(name: "scroll")
.overlay(
showFab ?
createFab()
: nil
, alignment: Alignment.bottomTrailing)
}
fileprivate func createFab() -> some View {
return Button(action: {
}, label: {
Image(systemName: "plus")
.font(.title)
.foregroundColor(.white)
.frame(width: 40, height: 40, alignment: .center)
})
.padding(8)
.background(Color.blue)
.cornerRadius(15)
.padding(8)
.shadow(radius: 3,
x: 3,
y: 3)
.transition(.scale)
}
}
struct ViewOffsetKey: PreferenceKey {
typealias Value = CGFloat
static var defaultValue = CGFloat.zero
static func reduce(value: inout Value, nextValue: () -> Value) {
value += nextValue()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
@markbattistella
Copy link

I know its been a little while but to solve the over scroll issue I changed lines 21-31 to:

.onPreferenceChange(ViewOffsetKey.self) { offset in
 withAnimation {
  if offset < 50 {
   showFab = true
  } else  {
   showFab = false
  }
 }
}

Then it appears on when near the top and off once passed the scroll point.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment