iosswiftswiftuiscrollviewpadding

Swift UI - Custom distance between keyboard and textfield


I have created a scroll view with multiple textfield in vertical stack.Scrolling is working perfect. After clicking on textfield it autoscrolled above keyboard, but I need more space between keyboard and text field. do we have any way in swift UI as we had before in UIKIT?

I observed that we have few scrollview function such as scrollTo(id:) but it is not fulfilling my need of having extra space between keyboard and text filed.

enter image description here


Solution

  • Check this out. here you can set keyBoardBottomPadding to change the padding

    import SwiftUI
    
    
    struct SwiftUIView: View {
        let displayName: String // Assuming this is passed in
        @State private var keyBoardBottomPadding: CGFloat = 0
        
        
        var body: some View {
            ScrollViewReader { _ in // The '_' means you're not explicitly using the proxy here
                ScrollView(showsIndicators: false) {
                    VStack(spacing: 8) { // Spacing looks like 8, not 16
                        // First TextField
                        
                        ForEach(0..<40) { index in
                            TextField("", text: .constant("test"))
                                .frame(height: 50)
                                .border(Color.gray, width: 2.0)
                        }
                    }
                    .onAppear(){
                        addKeyBoardObserver()
                    }
                    .onDisappear(){
                        removeKeyBoardObserver()
                    }
                    
                }
                .safeAreaPadding(.bottom, keyBoardBottomPadding)
            }
        }
        
        func addKeyBoardObserver(){
            // Add observers when the view appears
            NotificationCenter.default.addObserver(
                forName: UIResponder.keyboardWillShowNotification,
                object: nil,
                queue: .main
            ) { _ in
               
                self.keyBoardBottomPadding = 50
            }
            
            NotificationCenter.default.addObserver(
                forName: UIResponder.keyboardWillHideNotification,
                object: nil,
                queue: .main
            ) { _ in
                // Reset keyboardHeight when the keyboard hides
                self.keyBoardBottomPadding = 0
            }
        }
        func removeKeyBoardObserver() {
            // Remove observers when the view disappears to prevent memory leaks
            NotificationCenter.default.removeObserver(self)
        }
    }
    
    #Preview {
        SwiftUIView(displayName: "Your Text")
    }