MacOS上的SwiftUI:检测焦点变化并强制程序化地改变焦点。

问题描述 投票:0回答:1

我想检测一下 重点改变 并强行 重点改变. 在这个简单的例子中,我想检测用户是否点击了其中一个文本字段。另一方面,我想用一个按钮来设置焦点。

struct ContentView: View {

  @State private var textA = ""
  @State private var textB = ""

  @State private var focusableA = false
  @State private var focusableB = false

    var body: some View {
      VStack{
        HStack{
          TextField("Field A", text: $textA)
          .focusable(focusableA, onFocusChange: {f in print ("FocusChange A \(f)")})
          TextField("Field V", text: $textB)
          .focusable(focusableB, onFocusChange: {f in print ("FocusChange B \(f)")})
        }
        HStack{
          Button(action: {self.focusableA = true; self.focusableB = false }) 
          {Text("Set Focus to A")}
          Button(action: {self.focusableB = true; self.focusableA = false }) 
          {Text("Set Focus to B")
          }
        }
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
  }
}

上面的代码不工作,如何才能做到这一点。

macos keyboard swiftui focus
1个回答
1
投票

我想检测,如果用户点击其中一个文本字段。

下面是一个例子

TextField("Title", text: boundText, onEditingChanged: { editing in
            if editing {
                print(">> start editing, got focus")
            } else {
                print(">> end editing, lost focus")
            }
        })

我想用按钮来设置焦点的程序化。

SwiftUI本身暂时没有给出这方面的API。而 .focusable 给予 能力 视图的焦点,默认情况下不是这样的(如:文本),但不是强制设置焦点。

© www.soinside.com 2019 - 2024. All rights reserved.