SwiftUI中如何在Button嵌套的Popover内TextEditor输入空格?
你遇到的问题是因为父级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
相关产品推荐
相关产品推荐

