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

SwiftUI中如何在Button嵌套的Popover内TextEditor输入空格?

解决TextEditor输入空格触发父Button点击的问题

你遇到的问题是因为父级Button的点击手势会拦截TextEditor的空格按键事件(尤其在macOS平台,空格默认会触发Button的点击动作),导致空格无法输入到编辑器中,同时触发父Button的打印逻辑。以下是两种可行的解决方案:

方案一:popover显示时禁用父Button的点击响应

当弹出评论编辑的popover后,临时禁用父Button的点击检测,这样TextEditor的空格事件就不会被拦截:

struct ContentView: View {
    @State private var showPopoverComment = false
    
    var body: some View {
        Button(action: {
            print("parent button click")
        }) {
            VStack {
                Button("child button", action: {showPopoverComment = true})
                    .popover(isPresented: $showPopoverComment) {
                        EditCommentView()
                            .frame(width: 100, height: 100)
                    }
                // other views ...
            }
        }
        .buttonStyle(.plain)
        .allowsHitTesting(!showPopoverComment) // 添加该行,popover显示时父Button不响应点击
    }
}

方案二:让TextEditor优先处理空格事件

如果需要父Button在popover显示时仍能响应其他点击,可直接让TextEditor捕获空格事件,阻止其向上传递:

struct EditCommentView: View {
    @State var comment: String = ""
    var body: some View {
        TextEditor(text: $comment)
            .onKeyPress(.space) { _ in
                return .handled // 标记空格事件已处理,不再向上传递
            }
    }
}

注意:onKeyPress修饰符主要适用于macOS 13+、iOS 15+等较新系统版本,如果需要兼容旧版本,优先考虑方案一。

内容的提问来源于stack exchange,提问作者Sviatoslav

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 02:13:12