SwiftUI:如何强制 SwiftUI ContextMenu 预览占据整个宽度?

3

上下文

我目前正在使用新的SwiftUI ContextMenu,该菜单支持预览。但是,我发现很难让预览占满整个屏幕宽度。


代码

Text("Hello World")
    .contextMenu { menuItems } preview: { Text("Preview") }

问题

请注意:我已经尝试将.frame(maxWidth: .infinity)添加到Text("Preview"),但这并没有解决问题。

  • 如何强制预览占据整个屏幕的宽度?
2个回答

2
你可以将预览视图包裹在NavigationStack中。这很容易,但它不仅会水平扩展预览,还会垂直扩展,这可能不是你想要的。
另一种方法是设置预览的idealWidth:
import SwiftUI

struct ContentView: View {
  @State var viewWidth = CGFloat.zero

  var body: some View {
    VStack {
      VStack {
        Image(systemName: "globe")
          .imageScale(.large)
          .foregroundColor(.accentColor)
        Text("Long press me")
      }
      .contextMenu {
        Button("Action") {}
      } preview: {
        Text("Preview Text")
          .padding(.vertical, 50)
          .frame(idealWidth: viewWidth)
      }
    }
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .overlay {
      GeometryReader { geometry in
        Color.clear
          .onAppear {
            self.viewWidth = geometry.frame(in: .local).size.height
          }
      }
    }
  }
}

1
NavigationStack 解决了这个问题。 - Adel Bassiony

0

这已经被弃用了。在此输入图像描述

由于你没有提供太多代码,所以我使用了随机示例: 你可以像这样使用菜单:

struct MenuExample: View {

var body: some View {
    Menu {
        Button("Duplicate", action: duplicate)
        Button {
            rename()
        } label: { Label("rename", systemImage: "square.and.pencil") }
        Button {
            delete()
        } label: { Label("delete", systemImage: "trash") }
        
        Menu {
            Button("Open in Preview", action: openInPreview)
            Button("Save as PDF", action: saveAsPDF)
        } label: { Label("PDF", systemImage: "doc.fill") }
    } label: {
        Label("Menu", systemImage: "book.fill")
            .font(.title)
    }
    .foregroundColor(.orange)
    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
    .padding(30)
    .background(.orange.opacity(0.3))
  }

    func duplicate() {}
    func delete() {}
    func rename() {}
    func saveAsPDF() {}
    func openInPreview() {}
}

struct MenuTemp_Previews: PreviewProvider {
static var previews: some View {
    MenuExample()
 }
}

请问您能否提供链接,证明该方法已被弃用?我现在已经打开了文档,上面写着contextMenu(menuItems:preview:)是iOS 16.0的beta版。 - benjixinator
1
哦,你说得对,我是指附图中的那个。我还没有开始使用测试版,所以错过了那个,抱歉。 - Gal
弃用的方法的函数签名是什么? - benjixinator
1
你想要被弃用的API吗? 我认为它是:https://developer.apple.com/documentation/swiftui/view/contextmenu(_:)。 - Gal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接