如何在 SwiftUI 中使用键盘箭头滚动滚动视图中的项目?

2024-06-23

我已经使用 HStack for macOS 应用程序构建了一个具有水平类型滚动视图的视图。有没有办法使用键盘箭头圈出这些项目?

(我看到 ListView 有默认行为,但对于其他自定义视图类型则没有)

单击此处查看屏幕截图 https://share.cleanshot.com/BwEn6x

var body: some View {
   VStack {
     ScrollView(.horizontal, {
        HStack {
          ForEach(items.indices, id: \.self) { index in
               //custom view for default state and highlighted state
          }
        }
     }
    }
}


any help is appreciated :)

我使用的方法

  • 在按钮上使用键盘快捷键

替代方法

  • 使用命令(如何在 macOS 上的 SwiftUI 中检测键盘事件? https://stackoverflow.com/questions/61153562/how-to-detect-keyboard-events-in-swiftui-on-macos)

Code:

Model

struct Item: Identifiable {
    var id: Int
    var name: String
}

class Model: ObservableObject {
    @Published var items = (0..<100).map { Item(id: $0, name: "Item \($0)")}
}

Content

struct ContentView: View {
    
    @StateObject private var model = Model()
    @State private var selectedItemID: Int?
    
    var body: some View {
        VStack {
            Button("move right") {
                moveRight()
            }
            .keyboardShortcut(KeyEquivalent.rightArrow, modifiers: [])
            
            
            ScrollView(.horizontal) {
                LazyHGrid(rows: [GridItem(.fixed(180))]) {
                    ForEach(model.items) { item in
                        ItemCell(
                            item: item,
                            isSelected: item.id == selectedItemID
                        )
                        .onTapGesture {
                            selectedItemID = item.id
                        }
                    }
                }
            }
        }
    }
    
    private func moveRight() {
        if let selectedItemID {
            if selectedItemID + 1 >= model.items.count {
                self.selectedItemID = model.items.last?.id
            } else {
                self.selectedItemID = selectedItemID + 1
            }
        } else {
            selectedItemID = model.items.first?.id
        }
    }
}

Cell

struct ItemCell: View {
    let item: Item
    let isSelected: Bool
    var body: some View {
        ZStack {
            Rectangle()
                .foregroundColor(isSelected ? .yellow : .blue)
            Text(item.name)
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 SwiftUI 中使用键盘箭头滚动滚动视图中的项目? 的相关文章

随机推荐