'How do I make my own focusable view in SwiftUI using FocusState?

So I want to implement a custom control as a UIViewRepresentable which correctly handles focus using an @FocusState binding.

So I want to be able to manage the focus like so:

struct MyControl: UIViewRepresentable { ... }


struct Container: View {

    @FocusState var hasFocus: Bool = false

    var body: some View {
        VStack {
            MyControl()
                .focused($hasFocus)

            Button("Focus my control") {
                hasFocus = true
            }
        }
    }
}

What do I have to implement in MyControl to have it respond to the focus state properly? Is there a protocol or something which must be implemented?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source