我已經使用 HStack for macOS 應用程式構建了一個具有水平型別滾動視圖的視圖。有沒有辦法使用鍵盤箭頭圈出這些專案?
(我看到 ListView 具有默認行為,但對于其他自定義視圖型別則沒有)
單擊此處查看螢屏截圖
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 :)
uj5u.com熱心網友回復:
你可以試試這個示例代碼,使用我之前的帖子方法,但使用水平滾動視圖而不是串列。您必須將代碼調整為您的特定應用程式。我的方法只包含幾行監控關鍵事件的代碼。
import Foundation
import SwiftUI
import AppKit
struct ContentView: View {
let fruits = ["apples", "pears", "bananas", "apricot", "oranges"]
@State var selection: Int = 0
@State var keyMonitor: Any?
var body: some View {
ScrollView(.horizontal) {
HStack(alignment: .center, spacing: 0) {
ForEach(fruits.indices, id: \.self) { index in
VStack {
Image(systemName: "globe")
.resizable()
.scaledToFit()
.frame(width: 20, height: 20)
.padding(10)
Text(fruits[index]).tag(index)
}
.background(selection == index ? Color.red : Color.clear)
.padding(10)
}
}
}
.onAppear {
keyMonitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown]) { nsevent in
if nsevent.keyCode == 124 { // arrow right
selection = selection < fruits.count ? selection 1 : 0
} else {
if nsevent.keyCode == 123 { // arrow left
selection = selection > 1 ? selection - 1 : 0
}
}
return nsevent
}
}
.onDisappear {
if keyMonitor != nil {
NSEvent.removeMonitor(keyMonitor!)
keyMonitor = nil
}
}
}
}
uj5u.com熱心網友回復:
我使用的方法
- 在按鈕上使用鍵盤快捷鍵
替代方法
- 使用命令(如何在 macOS 上的 SwiftUI 中檢測鍵盤事件?)
代碼:
模型
struct Item: Identifiable {
var id: Int
var name: String
}
class Model: ObservableObject {
@Published var items = (0..<100).map { Item(id: $0, name: "Item \($0)")}
}
內容
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
}
}
}
細胞
struct ItemCell: View {
let item: Item
let isSelected: Bool
var body: some View {
ZStack {
Rectangle()
.foregroundColor(isSelected ? .yellow : .blue)
Text(item.name)
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/532914.html
上一篇:如何在SwiftUI中使用連續的文本視圖處理文本換行和對齊/填充?
下一篇:UIView對角線邊框在一個角上
