I have a custom list and I want to make the names in the list editable through double tap. I know how to solve this hacky ways. But are there no solid way to achieve this? like having .disabled without graying it out?
How to disable textfield without making it grayed out?
like having .disabled without graying it out?
That would be confusing for the user. It is very important to have a consistent.
I tried something. Let me know if that's what you are looking for:
struct ContentView: View {
@State private var theField: String = ""
@State private var disabledField = true
@State private var prompt: String = "disabled"
@FocusState private var focusedField: Int?
var body: some View {
TextField(prompt, text: $theField)
.frame(width: 200, height: 30)
.disabled(disabledField)
.focused($focusedField, equals: 1)
.overlay( // so the doubletap will be handled, even though textFied is disabled
RoundedRectangle(cornerRadius: 4)
.stroke(Color.gray, lineWidth: 1) // just to see, color can be set to bg or white
.offset(x: -5, y: 0)
.onTapGesture(count: 2) {
prompt = "Enter"
disabledField = false
focusedField = 2 // any value ≠ 1: to get the cursor appear when set to 1
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) { // delay to sequence focus changes and get cursor appear
focusedField = 1
}
}
)
}
}
You can set the color of the prompt so that it does not appear dimmed
TextField(prompt, text: $theField, prompt: Text(prompt).foregroundColor(.blue))
Have you explored using @FocusState
to programmatically control the focus of the TextField? The point here is that a TextField
needs to be in focus to accept input, and a user can move focus to the TextField by tapping on it.
You could also use the binding to a focusState
to determine the conditions and programmatically move focus.
You should check out FocusState and Focus Cookbook sample projects for example on how to control focus programmatically.