英文:
Context menu makes list disappear
问题
我想要一个上下文菜单来复制/粘贴表格数据。
import SwiftUI
struct SwiftUIView: View {
var body: some View {
List {
ItemView()
ItemView()
ItemView()
}
.contextMenu {
Button(action: {
}){
Text("复制")
}
}
}
}
struct ItemView: View {
var body: some View {
HStack{
Text("列 1")
Spacer()
Text("列 2")
Spacer()
Text("列 3")
}
}
}
struct SwiftUIView_Previews2: PreviewProvider {
static var previews: some View {
SwiftUIView()
}
}
然而,在长按列表时,列表会消失。我尝试仅使用 Text("列 1")
来确认 Spacer 是否引起了问题,结果仍然相同。
当使用 Grid
时似乎可以正常工作,但需要 iOS 16。
Grid {
GridRow {
ItemView()
}
GridRow {
ItemView()
}
}
.contextMenu {
Button(action: {
}){
Text("复制")
}
}
编辑:
在明亮的主题下,整个屏幕似乎都被选中。
添加 .frame(maxHeight: 200)
有时它可以工作,但我不知道我做了什么不同。
英文:
I want to have a context menu to copy/paste tabular data.
import SwiftUI
struct SwiftUIView: View {
var body: some View {
List {
ItemView()
ItemView()
ItemView()
}
.contextMenu {
Button(action: {
}){
Text("Copy")
}
}
}
}
struct ItemView: View {
var body: some View {
HStack{
Text("Column 1")
Spacer()
Text("Column 2")
Spacer()
Text("Column 3")
}
}
}
struct SwiftUIView_Previews2: PreviewProvider {
static var previews: some View {
SwiftUIView()
}
}
However, the list disappears when long pressing it. I tried using just Text("Column 1")
to confirm that the Spacers weren't causing issues and the same thing happened.
It seems to work when using a Grid
, but that requires iOS 16.
Grid {
GridRow {
ItemView()
}
GridRow {
ItemView()
}
}
.contextMenu {
Button(action: {
}){
Text("Copy")
}
}
Edit:
With light theme, it looks like the entire screen is getting selected.
Adding .frame(maxHeight: 200)
Sometimes it works, but I don't know what I did differently.
答案1
得分: 1
我相信这就是你要找的解决方案:
...
var body: some View {
List {
LazyVStack {
ForEach((0...3), id: \.self) { _ in
ItemView()
}
}
.contextMenu {
Button(action: {
}){
Text("复制")
}
}
}
}
...
你需要在列表内的视图中调用 contextMenu
。
英文:
I believe this is the solution you are looking for:
...
var body: some View {
List {
LazyVStack {
ForEach((0...3), id: \.self) { _ in
ItemView()
}
}
.contextMenu {
Button(action: {
}){
Text("Copy")
}
}
}
}
...
You need to call contextMenu
in a view inside the list.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论