FocusState not working on ipad

I created this simple view to test focus in preview mode and I have no idea why it works absolutely fine on iphone, but not at all on ipad?

import SwiftUI

struct SimpleFocusTestView: View {
 @FocusState private var isFocused: Bool

var body: some View {
    Text("Test Focus")
        .focusable()
        .focused($isFocused)
        .onTapGesture {
            isFocused.toggle()
            print("Tapped to toggle focus: \(isFocused)")
        }
        .onAppear { isFocused = true }
        .onChange(of: isFocused) { oldValue, newValue in
            print("Focus changed: \(newValue)")
        }
        .background {
          if isFocused {
            Capsule()
              .fill(.indigo)
              .opacity(0.3)
          }
        }
    }
}

#Preview {
    SimpleFocusTestView()
}

The printouts I get are:

if I click on ipad I get this:

Tapped to toggle focus: false Tapped to toggle focus: false Tapped to toggle focus: false

why is it impossible to change the value of isFocused on ipad? it all works fine on iphone:

Tapped to toggle focus: true Focus changed: false Tapped to toggle focus: false Focus changed: true

@hasen6 Do you mind testing this with a TextField instead of a Text to see if the focusState gets updated.

@DTS Engineer Hi, thanks for responding, I've been having trouble finding any kind of response to this whether on stackoverflow or from ChatGPT.

If I switch to TextField on iPhone it is focused onAppear, on iPad it is not, but if I click to focus it does manage to focus. So slightly better than just using a Text view, but the iPad behaviour is still different regarding focus. Not sure why this is?

The above code is the complete view, so can I ask, what happens for you with this code? Is this a problem unique to me if so I don't know why or does the same thing happen for you on iPad?

I arrived at the following conclusions after experimenting with a real iPad device and sims:

  • iPad devices use a different focus management system when a hardware keyboard is connected. The system often prioritises physical key inputs over programatically driven focus changes.
  • The FocusState can only be changed programmatically when the view is visible AND the physical keyboard is disconnected - to test this on a sim untick "Connect Hardware Keyboard".

Depending on your use case you might want to consider switching to a less pure SwiftUI approach. I am going to try using GCKeyboard with my use case being a virtual keyboard representing a classic 1980s home computer.

See my reply to a Stack Overflow post here for more details: https://stackoverflow.com/a/79009141/3719695

FocusState not working on ipad
 
 
Q