Last active
August 6, 2021 14:48
-
-
Save Amzd/d7d0c7de8eae8a771cb0ae3b99eab73d to your computer and use it in GitHub Desktop.
SwiftUI TextField has a very small tappable area and there is no simple way to make that area bigger. This is a solution using Introspect (https://github.com/siteline/SwiftUI-Introspect/) Stack Overflow question: https://stackoverflow.com/questions/56795712/swiftui-textfield-touchable-area/62089790#62089790
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension View { | |
public func textFieldFocusableArea() -> some View { | |
TextFieldButton { self.contentShape(Rectangle()) } | |
} | |
} | |
fileprivate struct TextFieldButton<Label: View>: View { | |
init(label: @escaping () -> Label) { | |
self.label = label | |
} | |
var label: () -> Label | |
private var textField = Weak<UITextField>(nil) | |
var body: some View { | |
Button(action: { | |
self.textField.value?.becomeFirstResponder() | |
}, label: { | |
label().introspectTextField { | |
self.textField.value = $0 | |
} | |
}).buttonStyle(PlainButtonStyle()) | |
} | |
} | |
/// Holds a weak reference to a value | |
public class Weak<T: AnyObject> { | |
public weak var value: T? | |
public init(_ value: T?) { | |
self.value = value | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct ExampleView: View { | |
@State var text: String = "" | |
var body: some View { | |
TextField("User ID", text: $text) | |
.padding(20) | |
.textFieldFocusableArea() // You can now tap in the 20 padding around the TextField and it will focus | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Okay but you have to attach a ResponderChain which is not in the above solution. Otherwise the environmentobject is empty and it crashes.