This is the 9th day of my participation in the August More Text Challenge. For details, see:August is more challenging
First, basic usage
struct ContentView: View {
@State var text: String = ""
var body: some View {
TextField("Please enter...", text: $text).padding()
}
}
Copy the code
- The first argument is
placeholder
. - The second parameter is the user input value, using
@State
addBinding
Bidirectional binding to monitor and change input values.
Two, listen to whether the user is in the write stateonEditingChanged
You can listen to whether the user is in the input state by giving the TextField parameter onEditingChanged.
TextField("Please enter...", text: $text) { editFlag in
print("Input status:\(editFlag)")}Copy the code
3. Monitor whether the user submits input
TextField("Please enter...", text: $text, onCommit: {
print("Submitted")})Copy the code
Four, style,textFieldStyle
SwiftUI currently supports four TextField styles:
DefaultTextFieldStyle
:iOS
Is equivalent toPlainTextFieldStyle
;macOS
Is equivalent toSquareBorderTextFieldStyle
PlainTextFieldStyle
: As the name implies, a text field style without any border, any color.RoundedBorderTextFieldStyle
: Added a rounded border.SquareBorderTextFieldStyle
:macOS
Unique.
5. CustomizeTextField
– search box
SwiftUI provides the most basic TextField usage, although RoundedBorderTextFieldStyle can realize the rounded borders, but you can’t add layer of magnifying glass and the delete button, need to achieve.
struct ContentView: View {
@State var text: String = ""
@State var editing: Bool = false
var body: some View {
ZStack(alignment: .center){
RoundedRectangle(cornerRadius: 10).stroke().frame(height:50).foregroundColor(.gray)
HStack{
Image(systemName: "minus.magnifyingglass").foregroundColor(.gray)
TextField("Please enter...", text: $text){editing in
self.editing = editing
}
if editing && !text.isEmpty{
Button(action: {
text = ""
}, label: {
Image(systemName: "xmark.circle.fill")
})
}
}.padding()
}.padding()
}
}
Copy the code
- use
ZStack
addRoundedRectangle
Implement rounded border. - through
TextField
theonEditingChanged
To listen for input. - By judging
if editing && ! text.isEmpty
Control whether the clear button is displayed.! text.isEmpty
Represents no input from the user on the text field. text = ""
Clear the text field.