MacOS 上的 SwiftUI:检测焦点变化并以编程方式强制焦点变化
SwiftUI on MacOS: Detect Focus Change and force Focus Change programaticly
我想检测 Focus Change 并强制执行 Focus Change.
在这个简单的示例中,我想检测用户是否点击了其中一个文本字段。
另一方面,我想用一个按钮以编程方式设置焦点。
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)
}
}
上面的代码不起作用,怎么办。
I want to detect, if a user clicks in one of the textfields.
这是一个例子
TextField("Title", text: boundText, onEditingChanged: { editing in
if editing {
print(">> start editing, got focus")
} else {
print(">> end editing, lost focus")
}
})
I want so set the focus programaticly with a Button
SwiftUI 本身暂时不为此提供 API。 .focusable
赋予 能力 可以聚焦视图,默认情况下不是这样(例如文本),但不是强制设置焦点。
我想检测 Focus Change 并强制执行 Focus Change.
在这个简单的示例中,我想检测用户是否点击了其中一个文本字段。
另一方面,我想用一个按钮以编程方式设置焦点。
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)
}
}
上面的代码不起作用,怎么办。
I want to detect, if a user clicks in one of the textfields.
这是一个例子
TextField("Title", text: boundText, onEditingChanged: { editing in
if editing {
print(">> start editing, got focus")
} else {
print(">> end editing, lost focus")
}
})
I want so set the focus programaticly with a Button
SwiftUI 本身暂时不为此提供 API。 .focusable
赋予 能力 可以聚焦视图,默认情况下不是这样(例如文本),但不是强制设置焦点。