英文:
`focused(_:equals)` not working but deprecated method is (`focusable(_:onFocusChanged:)`)
问题
以下是您提供的代码的翻译部分:
这是对我有效的重点代码:
```swift
struct ContentView1: View {
@State var text: String = "testing"
var body: some View {
VStack {
Text(text)
Text("top")
.padding()
.focusable(true, onFocusChange: { focused in
text = "top focus"
})
Text("bottom")
.padding()
.focusable(true, onFocusChange: { focused in
text = "bottom focus"
})
}
}
}
然而,我得到了关于.focusable(_:onFocusChange:)
行的弃用警告。因此,我自然而然地想要用非弃用的解决方案替代它。我发现这是使用@FocusState
和focused(_:equals:)
。所以我实现了这个:
struct ContentView2: View {
@FocusState var focus: Focus?
var body: some View {
VStack {
Text(focus?.rawValue ?? "no focus")
Text("top")
.padding()
.focused($focus, equals: .top)
Text("bottom")
.padding()
.focused($focus, equals: .bottom)
}
}
}
enum Focus: String {
case top = "top focus", bottom = "bottom focus"
}
但它根本不起作用。没有视图获得焦点。请注意,这是在 macOS 上运行的,我使用的是 13.0.1 版本。
请注意,我已经删除了HTML编码,以使翻译更清晰。如果您需要进一步的帮助,请告诉我。
<details>
<summary>英文:</summary>
Here is the focus code that works for me:
struct ContentView1: View {
@State var text: String = "testing"
var body: some View {
VStack {
Text(text)
Text("top")
.padding()
.focusable(true, onFocusChange: { focused in
text = "top focus"
})
Text("bottom")
.padding()
.focusable(true, onFocusChange: { focused in
text = "bottom focus"
})
}
}
}
However, I get a deprecation warning for the `.focusable(_:onFocusChange:)` lines. So naturally I go to replace it with the non-deprecated solution. I come to find out that that's using `@FocusState` and `focused(_:equals)`. So I implement this:
struct ContentView2: View {
@FocusState var focus: Focus?
var body: some View {
VStack {
Text(focus?.rawValue ?? "no focus")
Text("top")
.padding()
.focused($focus, equals: .top)
Text("bottom")
.padding()
.focused($focus, equals: .bottom)
}
}
}
enum Focus: String {
case top = "top focus", bottom = "bottom focus"
}
But it doesn't work at all. No views are getting focus. Keep in mind this is on macOS and I'm running 13.0.1.
</details>
# 答案1
**得分**: 1
确保每个`Text`视图都可以通过使用`.focusable()`修饰符来获得焦点。虽然某些视图,比如`TextField`,默认是可获得焦点的;但`Text`则不是:
```swift
VStack {
Text("top")
.focusable()
.focused($focus, equals: .top)
Text("bottom")
.focusable()
.focused($focus, equals: .bottom)
}
英文:
You want to make sure each Text
views are also focusable by using the .focusable()
modifier. While some views, such as TextField
, are focusable by default; Text
is not:
VStack {
Text("top")
.focusable()
.focused($focus, equals: .top)
Text("bottom")
.focusable()
.focused($focus, equals: .bottom)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论