繁体   English   中英

使用父子视图时如何在 SwiftUI 中给出条件?

[英]How to give condition in SwiftUI while using parent and child view?

我有如下自定义视图,我在另一个视图中使用

import SwiftUI

public struct TopSheet<Content >: View where Content : View {
    private var content: () -> Content
    
    @State private var arrowOffset: Double = 0
    
    public init(@ViewBuilder content: @escaping () -> Content) { self.content = content }
    
    public func expandRatio() -> Double { return max((currentHeight - minHeight) / contentHeight, 0) }
    
    public var body: some View {
        HStack(alignment: .center) {
            Arrow(offset: arrowOffset)
                .stroke(Color.pink, style: StrokeStyle(lineWidth: 4, lineCap: .round, lineJoin: .round))
                .frame(width: 30, height: 4)
            Spacer()
        }
    }
}

我在下方视图中使用上方视图

import SwiftUI

struct PassengerView: View {
    
    @State private var passengers: [String] = ["Joe Black", "Eva Green", "Jared Leto"]
    
    var body: some View {
        
        TopSheet {
            VStack {
                ForEach($passengers, id: \.self) { passenger in
                    HStack {
                        Text(passenger.wrappedValue)
                        Spacer()
                    }
                }
            }
            .padding(.horizontal, .afklPaddingL)
        }
    }
}

在这里,我想给出一个条件,只有当乘客人数大于 1 时, Topsheet中的Arrow()才应该可见。

我不确定我应该如何给出这个条件,因为两者都处于差异视图中。

尝试这个:

将 var 添加到您的TopSheet

var count: Int

将构造函数更改为:

public init(count: Int, @ViewBuilder content: @escaping () -> Content) {
    self.count = count
    self.content = content
}

和你的身体:

public var body: some View {
    HStack(alignment: .center) {
        if count > 1 {
            Arrow(offset: arrowOffset)
                .stroke(Color.pink, style: StrokeStyle(lineWidth: 4, lineCap: .round, lineJoin: .round))
                .frame(width: 30, height: 4)
        }
        Spacer()
    }
}

称它为:

TopSheet(count: passengers.count) {
            VStack {
........

由于passengers是一个@State变量,它会在更改时重新评估您的视图。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM