0
votes

I’ve got this little guy:

VStack(alignment: .leading, spacing: 4) {
    Text("Name")
        .font(.subheadline).bold()
    TextField("Name", text: self.$name)
}

and he looks like this: enter image description here

Now I want to increase the tap target so you can tap anywhere in the VStack to bring up the keyboard for the TextField. What’s a good way to do that?

I considered adding onTapGesture to the VStack but seems it’s not possible to trigger become first responder for TextFields, so seems I need to increase the TextField frame to have a larger tap target. Maybe put it in a ZStack instead with padding above, but a complication is how would I ensure it’s visually stacked below the header when the header height is dynamic? Perhaps contentShape could be used to somehow add padding to it?

1
SwiftUI TextField does not have capability for now to become focusable programmatically, so instead of workarounds I recommend to use UIViewRepresentable with UITextField for this purpose. There are a lot of posts on SO how to do this. - Asperi

1 Answers

0
votes

You can create subclass of UITextField and override point(inside:with:) method:

open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
    let bounds = self.bounds
    let extended = bounds.insetBy(dx: -10, dy: -10)
    let inside = extended.contains(point)
    return inside
}

and use your custom subclass of UITextField in SwiftUI. May be you have to create VStack subclass to allow touches outside of the VStack if touch lies in one of it subviews (with extended touch field).