Home > AI > IOS > SwiftUI >

(Example) scroll to stick


import SwiftUI


struct ContentView: View {
    @State var show: Bool = false
    @State var timer = Timer.publish(every: 0.1, on: .main, in: .tracking).autoconnect()
    @State var disabledHiddenView: Bool = false
    
    var body: some View {
        ZStack(alignment: .top) {
            
            ScrollView {
                VStack {
                    ForEach(0..<20) { idx in
                        Text(String(idx))
                    }
                    GeometryReader {geo in
                        
                        topView
                            .disabled(disabledHiddenView)
                                .onReceive(timer) { (_) in
                                    let y = geo.frame(in: .global).minY
                                    if y <= 0 {
                                        show = true
                                        disabledHiddenView = true
                                    } else {
                                        show = false
                                        disabledHiddenView = false
                                    }
                                }
                    }
                    .frame(width: UIScreen.main.bounds.width, height: 50)
                    

                    ForEach(20..<50) { idx in
                        Text(String(idx))
                    }
                }
            }
            
            if show {
                topView
            }
        }
    }
    
    
    var topView: some View {
        Text("good")
            .frame(width: UIScreen.main.bounds.width, height: 50)
            .background(Color.orange)
            .edgesIgnoringSafeArea(.all)
            .onTapGesture {
                print("goood")
            }
    }
}

Leave a Reply