在文本字段处于活动状态时,SwiftUI macOS使用箭头键滚动列表 [英] SwiftUI macOS Scroll a List With Arrow Keys While a TextField is Active

查看:68
本文介绍了在文本字段处于活动状态时,SwiftUI macOS使用箭头键滚动列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用SwiftUI

我玩过 onMoveCommand focusable ,并对父项" NSWindow ,但是还没有找到一种清晰明显的方式让 TextField 不断接受输入,同时仍然能够导航底层的 List 使用向上和向下箭头键.以下代码允许在 TextField 中输入文本,或在其中导航列表条目,但不能同时在两者之间...

  struct ContentView:视图{@State var text:字符串="@State var selection:Int?= 1var body:some View {VStack {TextField(输入文字",文字:$ text)列表(选择:$ selection){ForEach((1 ... 100),id:\ .self){文字("\($ 0)")}}}}} 

解决方案

您可以将NSTextField包裹在NSViewRepresentable中,并使用NSTextFieldDelegate截取上移键和下移键.您可以看一下我的建议演示.

带有建议的文本字段的来源

I'd like to use a SwiftUI TextField and a SwiftUI List to render a "search box" above a list of items. Something roughly like the search box available in Safari's Help menu item...which provides a search box where you can always enter text while simultaneously browsing through the list of results using the up and down arrow keys.

I've played with onMoveCommand, focusable, and adjustments to the "parent" NSWindow, but haven't found a clear and obvious way for the TextField to constantly accept input while still being able to navigate the underlying List using the up and down arrow keys. The following code allows for either text to be entered in the TextField, or list entries to be navigated through, but not both at the same time...

struct ContentView: View {

  @State var text: String = ""
  @State var selection: Int? = 1

  var body: some View {
    VStack {
      TextField("Enter text", text: $text)
      List(selection: $selection) {
        ForEach((1...100), id: \.self) {
          Text("\($0)")
        }
      }
    }
  }
}

解决方案

You can wrap a NSTextField in a NSViewRepresentable and use the NSTextFieldDelegate to intercept the move up and down keys. You can take a look into my suggestions demo.

Source of a text field with suggestions

这篇关于在文本字段处于活动状态时,SwiftUI macOS使用箭头键滚动列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆