首页 > 解决方案 > 将 NavigationLink 添加到 GroupBox

问题描述

我希望能够单击 GroupBox 并将我导航到另一个视图。我尝试实现以下代码并得到错误:

  1. 无法将“NavigationLink<Text, some View>”类型的值转换为预期的参数类型“GroupBoxStyleConfiguration”
  2. 类型 '() -> ()' 不能符合 'StringProtocol';只有结构/枚举/类类型可以符合协议

我想知道是否有一种方法可以使用 Groupboxes 来更改视图,如果可以,如何?

import SwiftUI

struct ContentView: View {
    // MARK - Properties
    @Environment(\.presentationMode) var presentationMode
    
    var body: some View {
        NavigationView {
          ScrollView(.vertical, showsIndicators: false) {
            VStack(spacing: 10) {
        // MARK: - SECTION 1 : Daily Catch-up
                GroupBox(
// The errors start below 
                    NavigationLink({
                        WellnessLabelView(labelText: "Daily Catch-up", labelImage: "chevron.right")
                        ) {
                            Divider().padding(.vertical, 4)
                            HStack(alignment: .center, spacing: 10) {
                                Text("This app was developed with the idea that expectant families deserve easy access to resources.")
                                    .font(.footnote)}
                        }

标签: swiftuigroupboxswiftui-navigationlink

解决方案


你必须自己制作GroupBoxStyle https://itnext.io/swiftui-groupbox-for-ios-bb16aa71469c

struct HealthGroupBoxStyle<V: View>: GroupBoxStyle {
var color: Color
var destination: V
var date: Date?

@ScaledMetric var size: CGFloat = 1

func makeBody(configuration: Configuration) -> some View {
    NavigationLink(destination: destination) {
        GroupBox(label: HStack {
            configuration.label.foregroundColor(color)
            Spacer()
            if date != nil {
                Text("\(date!)").font(.footnote).foregroundColor(.secondary).padding(.trailing, 4)
            }
            Image(systemName: "chevron.right").foregroundColor(Color(.systemGray4)).imageScale(.small)
        }) {
            configuration.content.padding(.top)
        }
    }.buttonStyle(PlainButtonStyle())
}
}

推荐阅读