You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 17:32:33