SwiftUI中@FocusState聚焦环异常问题排查
SwiftUI @FocusState 多按钮聚焦异常问题修复
问题原因
你手动给Button添加了.focusable()修饰符,这会干扰SwiftUI Button组件默认的聚焦行为。Button本身已经内置了可聚焦特性,重复添加.focusable()会导致ForEach循环内的按钮无法正确绑定@FocusState的状态更新,只有第一个按钮能触发聚焦环显示。
修复方法
直接移除.focusable()修饰符即可,保留.focused($buttonFocusState, equals: button)的绑定逻辑。修改后的代码如下:
enum ButtonTab: Int, CaseIterable, Hashable, Identifiable { public var id: Self { return self } public var buttonTitle: String { switch self { case .one: return "One" case .two: return "Two" case .three: return "Three" case .four: return "Four" case .five: return "Five" } } case one, two, three, four, five } struct ButtonTagsContentView: View { @FocusState var buttonFocusState: ButtonTab? var body: some View { VStack { HStack { ForEach(ButtonTab.allCases, id: \.self) { button in Button(button.buttonTitle) { print("\(button) selected") buttonFocusState = button } .focused($buttonFocusState, equals: button) } } .padding() } } }
补充说明
如果需要自定义按钮的聚焦优先级,可以给.focused()添加priority参数,无需手动添加.focusable()。例如:
.focused($buttonFocusState, equals: button, priority: 1)
内容的提问来源于stack exchange,提问作者Z S
相关产品推荐
相关产品推荐

