This is an approach to get live input predictions/ auto completion of a SwiftUI TextField
Copy the file PredictingTextField.swift
into your Project and use it by calling a
struct MyView: View {
@State var predictableValues: Array<String> = []
@State var myPredictedValues: Array<String> = []
/// Empty to start with. Will populate once user starts typing
@State var textFieldInput: String = ""
var body: some View {
PredictingTextField(predictableValues: self.$predictableValues,
predictedValues: self.$myPredictedValues,
textFieldInput: self.$textFieldInput
)
}
}
You can and need to pass it the following variables:
predictableValues
->@Binding Array<String>
Needs to be an Array of Strings as we compare the input of theTextField
which also is a String to these Strings. It can be only one Item in the Array or an empty array. In the later case theTextField
will not make any predictions and the use of a normalTextField
is recommended.predictedValues
->@Binding Array<String>
This also needs to be an Array of Strings. Should be empty when initialized. In here will be the prediction/ -s of the input of theTextField
based on the predictableValues. It is given as attribute so the predictions can be accessed on the parent view.textFieldInput
->@Binding String
This is the text that is currently in theTextField
(This is a parameter that is also used in the Swift implementation ofTextField
() ). It is provided as Binding Object so it can be reset from the parent view. If e.g. one wants to reset the input of theTextField
once a prediction was made/ selected/ used.
textFieldTitle
->String?
Use this to set a Title in an untouchedTextField
predictionInterval
->@State Double?
This can be modified to accelerate or slower the prediction. Default is a predicition made every 0.1 seconds.
Note: If the TextField
gets multiple inputs at once. E.g. in form of a String separated by spaces it will make predictions on every SubString of that input and append these predictions to the predictedValues Array. Altough every prediction will only occure once in the predictedValues
.