SwiftUI中.onKeyPress在.repeat阶段无法更新@Binding变量的问题
SwiftUI .onKeyPress 修改@Binding变量时按键重复失效问题
在SwiftUI中,使用.onKeyPress闭包修改视图自身定义的@State变量时,按住按键可正常触发重复更新;但如果修改的是@Binding绑定的外部变量,该变量仅能更新一次,按住对应按键时无法触发后续的重复更新。
已向Apple提交Bug反馈:FB14751737
代码示例
import SwiftUI struct ContentView: View { @State var doubleValue: Double = 1.0 var body: some View { VStack { Text("Focus the value and press and hold either <- left arrow or right arrow ->") HStack{ Text("Repeats don't work: "); DoesntWork(doubleValue: $doubleValue) } }.monospaced() } } struct DoesntWork: View { @Binding var doubleValue: Double var body: some View { Text("\(doubleValue)") .focusable() .onKeyPress( keys: [.leftArrow,.rightArrow], phases: [.down, .repeat] ) {keyPress in if keyPress.key == .leftArrow { doubleValue -= 1} else { doubleValue += 1} // only works once - ignores repeats return .handled } } }
已确认的受影响版本
- macOS 14.6.1 搭配 Xcode 16-beta-4
- macOS 15.1 beta 搭配 Xcode 16.1 beta (16B5001e)
内容的提问来源于stack exchange,提问作者Disco
相关产品推荐
相关产品推荐

