问题: 更新到 Swift 6 和 iOS 18 后,菜单组件的交互行为不符合预期。当用户点击菜单时,onTapGesture 和 PrimaryAction 无法正常工作以触发所需的操作。
代码示例:
将 onTapGesture 与菜单一起使用(不起作用):
Menu {
Button(action: {}) {
Label("Add to Reading List", systemImage: "eyeglasses")
}
Button(action: {}) {
Label("Add Bookmarks for All Tabs", systemImage: "book")
}
Button(action: {}) {
Label("Show All Bookmarks", systemImage: "books.vertical")
}
} label: {
Label("Add Bookmark", systemImage: "book")
} onTapGesture: {
print("Print on tap gesture")
}
使用primaryAction(菜单不出现,但点击时会触发操作):
Menu {
Button(action: {}) {
Label("Add to Reading List", systemImage: "eyeglasses")
}
Button(action: {}) {
Label("Add Bookmarks for All Tabs", systemImage: "book")
}
Button(action: {}) {
Label("Show All Bookmarks", systemImage: "books.vertical")
}
} label: {
Label("Add Bookmark", systemImage: "book")
} primaryAction: {
print("Primary action triggered")
}
尝试覆盖点击区域(无效果):
ZStack {
Menu {
Button(action: {}) {
Label("Add to Reading List", systemImage: "eyeglasses")
}
Button(action: {}) {
Label("Add Bookmarks for All Tabs", systemImage: "book")
}
Button(action: {}) {
Label("Show All Bookmarks", systemImage: "books.vertical")
}
} label: {
Label("Add Bookmark", systemImage: "book")
}
Color.clear
.contentShape(Rectangle())
.onTapGesture {
print("Tap gesture recognized")
}
}
请帮忙。
当用户点击菜单时如何开始操作?
iOS 18 更新上市后我也遇到了同样的问题。我在 swiftUI 中的项目,我在 Textflied、图像和文本上多次使用了 onTap 手势识别修饰符。
这些都是有问题的,当点击它很多次时它会卡住,有时却工作正常。所以我想出了这个解决方案,而不是使用 onTapGesture 修饰符,我使用 highPriorityGesture 它对我来说效果很好尝试这个我希望它能解决你的问题。
.highPriorityGesture(
TapGesture().onEnded {
print("Tap gesture recognized")
}
)