简体   繁体   中英

SwiftUI Show and Dismiss Textfield Keyboard

I try to show the text field keyboard as soon as the view appears and dismiss the keyboard when tap on the keyboard "return" key, the first part of the problem is solved by the code example bellow, But that make the keyboard "return" key doesn't work, Did any one can help to achieve my to show and dismiss the textfiled keyboard as I need.

import SwiftUI

struct MyTextField: UIViewRepresentable {
    typealias UIViewType = UITextField
    
    @Binding var becomeFirstResponder: Bool
    
    func makeUIView(context: Context) -> UITextField {
        let textField = UITextField()
        return textField
    }
    
    func updateUIView(_ textField: UITextField, context: Context) {
        if self.becomeFirstResponder {
            DispatchQueue.main.async {
                textField.becomeFirstResponder()
                self.becomeFirstResponder = false
            }
        }
    }
}

struct TextFieldFirstResponder: View {
    
    @State private var becomeFirstResponder = false
    
    var body: some View {
        
        MyTextField(becomeFirstResponder: self.$becomeFirstResponder)
            .onAppear {
                self.becomeFirstResponder = true
            }
    }
}

Use textFieldShouldReturn delegate method. For this make Coordinator for UIViewRepresentable.

struct MyTextField: UIViewRepresentable {
    typealias UIViewType = UITextField
    
    @Binding var becomeFirstResponder: Bool
    
    func makeUIView(context: Context) -> UITextField {
        let textField = UITextField()
        textField.delegate = context.coordinator
        return textField
    }
    
    func updateUIView(_ textField: UITextField, context: Context) {
        if self.becomeFirstResponder {
            DispatchQueue.main.async {
                textField.becomeFirstResponder()
                self.becomeFirstResponder = false
            }
        }
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(parent: self)
    }

    class Coordinator: NSObject, UITextFieldDelegate {
        var parent: MyTextField
        
        init(parent: MyTextField) {
            self.parent = parent
        }
        
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            textField.resignFirstResponder()
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM