1.1 C
New York
Sunday, February 23, 2025

ios – Preserve scroll place when new objects are added to prime of the record


I’m having a difficulty with preserving the record view ‘frozen’ in place when new objects are added if the person has scrolled right down to view and merchandise. Right here is the code that I’m at the moment utilizing:

import SwiftUI

struct MessageList: View {
    @ObservedObject var socketManager: WebSocketManager
    @State var isUpdating: Bool = false
    @State non-public var currentOffset: CGFloat = 0
    @State non-public var currentScrollID: UUID?
    
    @State non-public var timer: Timer? = nil
    
    func simulateMessages(){
        timer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { _ in
            let newItem = Message(content material: "Whats up", sentFlag: true)
            socketManager.messages.append(newItem)
        }
    }
    
    func stopSimulation(){
        timer?.invalidate()
        timer = nil
    }
    
    var physique: some View {
        Button{
            if isUpdating{
                stopSimulation()
            } else {
                simulateMessages()
            }
            
            isUpdating.toggle()
            
        } label: {
            Textual content(isUpdating ? "Cease" : "Replace")
        }
        
        Record(socketManager.messages.reversed(), id: .uuid) { message in
            messageView(message: message)
                .swipeActions(edge: .trailing) {
                    DeleteButton(socketManager: socketManager, message: message)
                }
                .swipeActions(edge: .main){
                    SaveButton(socketManager: socketManager, message: message)
                }
                .contextMenu{
                    SaveButton(socketManager: socketManager, message: message)
                    DeleteButton(socketManager: socketManager, message: message)
                }
        }

    }
}
#Preview {
    let socketManager = {
        let supervisor = WebSocketManager()
        supervisor.messages = [Message(content: "Hello, World! nthis is a long message nThis nnew linenanbncnd", sentFlag: true),
                            Message(content: "Hello, World! nthis is a long message nThis nnew linenanbncnd", sentFlag: false)]
        return supervisor
    }()
    MessageList(socketManager: socketManager)
}

I experimented with this resolution. Nonetheless, this makes use of a lazyVStack and I want to hold the record if potential for styling and the swipe actions.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles