SwiftUI inputAccesoryView Implementation

后端 未结 4 1015
感动是毒
感动是毒 2021-01-07 07:58

I am trying to implement an inputAccessoryView on a TextField in SwiftUI. The goal is to have a \"Done\" Button appear above the Keyboard which when pressed gets rid of the

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-07 08:18

    I've solved this problem using 99% pure SwiftUI on iOS 14. That's my implementation:

    import SwiftUI
    
     struct ContentView: View {
    
        @State private var showtextFieldToolbar = false
        @State private var text = ""
    
        var body: some View {
        
            ZStack {
                VStack {
                    TextField("Write here", text: $text) { isChanged in
                        if isChanged {
                            showtextFieldToolbar = true
                        }
                    } onCommit: {
                        showtextFieldToolbar = false
                    }
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .padding()
                }
            
                 VStack {
                    Spacer()
                    if showtextFieldToolbar {
                        HStack {
                            Spacer()
                            Button("Close") {
                                showtextFieldToolbar = false
                                UIApplication.shared
                                        .sendAction(#selector(UIResponder.resignFirstResponder),
                                                to: nil, from: nil, for: nil)
                            }
                            .foregroundColor(Color.black)
                            .padding(.trailing, 12)
                        }
                        .frame(idealWidth: .infinity, maxWidth: .infinity,
                               idealHeight: 44, maxHeight: 44,
                               alignment: .center)
                        .background(Color.gray)   
                    }
                }
            }
        }
    }
    
     struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }
    

提交回复
热议问题