SwiftUI - Textfield return key event
you could try something like this:
struct QuestionItemView: View {
@State private var question: Question?
@State private var answer = ""
@State private var imgType = ""
var body: some View {
VStack(spacing: 30) {
GroupBox {
if let question = question {
Text(question.question)
.font(.largeTitle)
.fontWeight(.heavy)
.scaledToFit()
.frame(width: 300, height: 100)
.cornerRadius(12)
}
}
GroupBox {
TextField("Enter your answer", text: $answer)
.frame(width: 300)
.font(.title2)
.scaledToFit()
.cornerRadius(12)
.multilineTextAlignment(.center)
.onSubmit { // <--- only on pressing the return key
// .onChange(of: answer) { _ in // <-- as you type
// .onReceive(answer.publisher) { _ in // <-- as you type
if answer == question?.answer {
imgType = "circle"
print("o")
} else {
imgType = "multiply"
print("x")
}
}
}
if imgType == "circle" {
Image(systemName: "circle")
} else {
Image(systemName: "multiply")
}
}
.frame(width: 240)
.background(RoundedRectangle(cornerRadius: 7.0).fill(Color.white))
.onAppear {
let questions: [Question] = Bundle.main.decode("questions.json")
question = questions.randomElement()
}
}
}
If you are on an older system, you may need to do this:
TextField("Enter your answer", text: $answer, onCommit: {
if answer == question?.answer {
imgType = "circle"
print("o")
} else {
imgType = "multiply"
print("x")
}
})
swiftUI how to have search button on keyboard
If I understand correctly you want to change the UIReturnKeyType
.
In that case you have to use UIKit since there isn't yet any option to change the type of return key in SwiftUI.
To do this, you have to make a custom TextField using UIIKit and then modify it the way you like.
Also keep in mind that the UIReturnKeyType
enum is under discussion and may replace with a different implementation.
// MARK: Custom TextField
struct TextFieldTyped: UIViewRepresentable {
let keyboardType: UIKeyboardType
let returnVal: UIReturnKeyType
let tag: Int
@Binding var text: String
@Binding var isfocusAble: [Bool]
func makeUIView(context: Context) -> UITextField {
let textField = UITextField(frame: .zero)
textField.keyboardType = self.keyboardType
textField.returnKeyType = self.returnVal
textField.tag = self.tag
textField.delegate = context.coordinator
textField.autocorrectionType = .no
return textField
}
func updateUIView(_ uiView: UITextField, context: Context) {
if isfocusAble[tag] {
uiView.becomeFirstResponder()
} else {
uiView.resignFirstResponder()
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UITextFieldDelegate {
var parent: TextFieldTyped
init(_ textField: TextFieldTyped) {
self.parent = textField
}
func updatefocus(textfield: UITextField) {
textfield.becomeFirstResponder()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if parent.tag == 0 {
parent.isfocusAble = [false, true]
parent.text = textField.text ?? ""
} else if parent.tag == 1 {
parent.isfocusAble = [false, false]
parent.text = textField.text ?? ""
}
return true
}
}
}
And you can use it like this:
(Change the returnVal
to .search
in your case.)
struct CustomeKT: View {
@State var myTextForTX = ""
@State var focused: [Bool] = [false, true]
var body: some View {
TextFieldTyped(keyboardType: .default, returnVal: .search, tag: 0, text: self.$myTextForTX, isfocusAble: self.$focused)
}
}
How to navigate through SwiftUI TextFields by clicking on return button from keyboard?
To resolve your two problems, you need to work with UIKit from SwiftUI. First, you need to customized TextField using UIViewRepresentable. Here is the sample code for test purposes though the code is not so elegance. I bet, there will be having a more robust solution.
- Inside the customized TextFieldType, the Keyboard return type has
been set. - By using object binding and delegate methods
textFieldShouldReturn, View can focus the keyboard by updating the binding variables.
Here is the sample code:
import SwiftUI
struct KeyboardTypeView: View {
@State var firstName = ""
@State var lastName = ""
@State var focused: [Bool] = [true, false]
var body: some View {
Form {
Section(header: Text("Your Info")) {
TextFieldTyped(keyboardType: .default, returnVal: .next, tag: 0, text: self.$firstName, isfocusAble: self.$focused)
TextFieldTyped(keyboardType: .default, returnVal: .done, tag: 1, text: self.$lastName, isfocusAble: self.$focused)
Text("Full Name :" + self.firstName + " " + self.lastName)
}
}
}
}
struct TextFieldTyped: UIViewRepresentable {
let keyboardType: UIKeyboardType
let returnVal: UIReturnKeyType
let tag: Int
@Binding var text: String
@Binding var isfocusAble: [Bool]
func makeUIView(context: Context) -> UITextField {
let textField = UITextField(frame: .zero)
textField.keyboardType = self.keyboardType
textField.returnKeyType = self.returnVal
textField.tag = self.tag
textField.delegate = context.coordinator
textField.autocorrectionType = .no
return textField
}
func updateUIView(_ uiView: UITextField, context: Context) {
if isfocusAble[tag] {
uiView.becomeFirstResponder()
} else {
uiView.resignFirstResponder()
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UITextFieldDelegate {
var parent: TextFieldTyped
init(_ textField: TextFieldTyped) {
self.parent = textField
}
func updatefocus(textfield: UITextField) {
textfield.becomeFirstResponder()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if parent.tag == 0 {
parent.isfocusAble = [false, true]
parent.text = textField.text ?? ""
} else if parent.tag == 1 {
parent.isfocusAble = [false, false]
parent.text = textField.text ?? ""
}
return true
}
}
}
Output:
Change 'Return' button function to 'Done' in swift in UITextView
You can set the return key type of the text field:
textField.returnKeyType = UIReturnKeyType.done
Update
You can definitely use the same approach to set the return key to "Done", as mentioned above. However, UITextView doesn't provide a callback when user hits the return key. As a workaround, you can try to handle the textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) delegate call, and dismiss the keyboard when you detect the input of a new line character:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if (text == "\n") {
textView.resignFirstResponder()
}
return true
}
Related Topics
Macos/Swift Capture Audio with Avcapturesession
Hstack with Sf Symbols Image Not Aligned Centered
Undefined Behavior, Or: Does Swift Have Sequence Points
Create Skscene Subclasses Programmatically, Without Size Info
How to Create Text File for Writing
Xcode 8.2.1 Not Showing Documentation Description on Autocomplete
Swift Lazy Subscript Ignores Filter
Navigationview Doesn't Display Correctly When Using Tabview in Swiftui
How to Handle Multiple Network Call in Alamofire
Swift 4 Codable - API Provides Sometimes an Int Sometimes a String
How to Make Alphabetically Section Headers in Table View with a Mutable Data Source
Adjust Nsvisualeffectview Blur Radius and Transparency
How to Add Constraints Programmatically to My Uilabel
How to Connect Aksequencer to a Akcallbackinstrument
Is It the Right Way Using '[Weak Self]' in Swift Closure
Adding a View to the Window Hierarchy
Avspeechutterance - Swift - Initializing with a Phrase
The File "Xxx.Mp4" Couldn't Be Opened Because You Don't Have Permission to View It