English 中文(简体)
快速的IOS TabView with .tabViewStyle (page) not Letting text Field/key板 work
原标题:Swift IOS TabView with .tabViewStyle(.page) not letting TextField/keyboard work correctly

我有一View意见,其中一则意见有正文。 在我点击文本现场时,关键板块是文本现场。 然而,如果我从TabViewStyle(页)中删除,那么一切照样工作! 兹随函附上下文表。 希望得到任何帮助。

struct ContentView: View {
    init() {
        UIPageControl.appearance().currentPageIndicatorTintColor = UIColor(Color.red)
        UIPageControl.appearance().pageIndicatorTintColor = UIColor.lightGray
        UIPageControl.appearance().tintColor = UIColor.lightGray
    }

    var body: some View {
        TabView{
            anotherView()
            TextView()
            anotherView()
        }
        .edgesIgnoringSafeArea(.all)
        .padding(.bottom, 20)
        .frame(
            width: UIScreen.main.bounds.width ,
            height: UIScreen.main.bounds.height
        )
        .tabViewStyle(.page) // issue here but I need the page style
        .indexViewStyle(.page(backgroundDisplayMode: .interactive))
    
    }
 
}
struct TextView: View {
    @State var textInput = ""

    var body: some View {
        VStack{
            Spacer()
            TextField("textfield", text: $textInput)
        }
        .padding()
    }
}

[“gif”/]

如果我删除了这段话,那么它就发挥了作用。 然而,我需要wi子和键盘不要阻挡案文的现场。

问题回答

问题在于用“TabaView”的页,我确实增加了一个变体,这样,当关键板看上去时,就把这一观点推到关键板上。

import SwiftUI
//import Combine


struct KeyboardResponsiveModifier: ViewModifier {
    
    /*
        IMPORTANT: I had an issue using the .tabViewStyle(.page) on TabView; issue was when I clicked on the
        TextField in the TabView the keyboard would block the TextField, this struct help solve that issue, by
        moving the view up so that when the keyboard appears it doesn t block the textField
     */
    
    @State private var textFieldPosition: CGFloat = 0
    @State private var textFieldHeight: CGFloat = 0
    
    @State private var offset: CGFloat = 0
    
    func body(content: Content) -> some View {
        content
            .padding(.bottom, offset)
            .overlay(
                GeometryReader { proxy in
                    Color.clear
                        .onAppear {
                            textFieldPosition = proxy.frame(in: .global).minY
                            textFieldHeight = proxy.size.height
                        }
                }
            )
            .onAppear(perform: subscribeToKeyboardEvents)
    }
    
    private func calculateOffset(with keyboardHeight: CGFloat, screenHeight: CGFloat) -> CGFloat {
        let adjustedPosition = screenHeight - textFieldPosition - textFieldHeight
        let newOffset =  keyboardHeight - adjustedPosition
        return newOffset
    }
    
    private func subscribeToKeyboardEvents() {
        NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { notification in
            guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
            let screenHeight = UIScreen.main.bounds.height
            let keyboardHeight = keyboardFrame.height
//            withAnimation(.linear(duration: 0.05)) {
            // when the keyboard popups up moves the view up so that the TextField is visible above the keyboard
            offset = calculateOffset(with: keyboardHeight, screenHeight: screenHeight)
//            }
        }
        
        NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { _ in
//            withAnimation(.linear(duration: 0.05)) {
                offset = 0 // when the keyboard disappears it moves the view back down
//            }
        }
    }
}

extension View {
    func keyboardResponsive() -> some View {
        self.modifier(KeyboardResponsiveModifier())
    }
}


struct TextView: View {
    @State var textInput = ""
    @State private var isKeyboardVisible = false

    
    var body: some View {
        ScrollViewReader { proxy in
            GeometryReader { geometry in
                ScrollView {
                    VStack{
                        Spacer()
                        TextField("Prompt", text: $textInput, axis: .vertical)
                            .padding(EdgeInsets(top: 10, leading: 15, bottom: 10, trailing: 15))
                            .overlay(
                                RoundedRectangle(cornerRadius: 14)
                                    .stroke(Color.red, lineWidth: 1)
                            )
                            .autocapitalization(.none) //stops the auto capitilize of words
                            .autocorrectionDisabled()
                            .foregroundColor(Color.black)
                            .padding( .bottom, isKeyboardVisible ? 10 : 0) // give a little padding when the keyboard appears
                            .id("TextFieldID")

                    }
                    .frame(width: geometry.size.width, height: geometry.size.height)
                }
                .keyboardResponsive() // Apply the custom modifier here
                .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { _ in
                    isKeyboardVisible = true
                    withAnimation { // scroll to the bottom so that it doesn t appear as tho the keyboard is overlapping the TextField
                        proxy.scrollTo("TextFieldID", anchor: .bottom)
                    }
                }
                .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in
                    isKeyboardVisible = false
                }
            }
        }
    }
}

#Preview {
    TextView()
}




相关问题
SwiftUI: How do I position a button x points above a sheet?

I am trying to recreate a Maps-style UI with a persistent bottom sheet and controls fixed above. Apple Maps UI with controls above ☝️ Example here, the "Look Around" binoculars button and ...

BraintreeDropIn deprecated functions error

I m getting this error on the latest release of BraintreeDropIn, I really don t get it since based on the patch notes, this should ve been addressed already, I have already tried cleaning derived data,...

how to limit zoom level in map swift ui?

how to limit zoom level in map swift ui i have map and need to make zoom level limited Map(coordinateRegion: $region,annotationItems: viewModel.nearbyGyms) { item in ...

UIImageView - How to get the file name of the image assigned?

Is it possible to read the name of an UIImageView s UIImage that s presently stored in the UIImageView? I was hoping you could do something kind of like this, but haven t figured it out. NSString *...

热门标签