Skip to content

Instantly share code, notes, and snippets.

@cutiko
Last active April 17, 2024 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cutiko/06902d957f8f75363c2539938df1286f to your computer and use it in GitHub Desktop.
Save cutiko/06902d957f8f75363c2539938df1286f to your computer and use it in GitHub Desktop.
On Focus Lost iOS and Android
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun SimpleInput(onFocusLost: ()-> Unit) {
var textValue by remember { mutableStateOf("") }
var previousFocus by remember { mutableStateOf(false) }
TextField(
value = textValue,
onValueChange = { textValue = it },
modifier = Modifier.onFocusChanged { it: FocusState ->
if (previousFocus && it.isFocused.not()) {
onFocusLost()
}
previousFocus = it.isFocused
}
)
}
private struct SimpleInput: View {
@State private var text: String = ""
@FocusState private var isFocused: Bool
private let onFocusLost: () -> Void
@State private var previousFocus = false
init(onFocusLost: @escaping () -> Void) {
self.onFocusLost = onFocusLost
}
var body: some View {
TextField(
"INPUT:",
text: $text
)
.focused($isFocused)
.onChange(of: isFocused) { newFocus in
if (previousFocus && !newFocus) {
self.onFocusLost()
}
previousFocus = newFocus
}
}
}
private struct SimpleInput: View {
@State private var text: String = ""
@FocusState private var isFocused: Bool
private let onFocusLost: () -> Void
init(onFocusLost: @escaping () -> Void) {
self.onFocusLost = onFocusLost
}
var body: some View {
TextField(
"INPUT:",
text: $text
)
.focused($isFocused)
.onChange(of: isFocused) { previousFocus, newFocus in
if (previousFocus && !newFocus) {
self.onFocusLost()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment