簡體   English   中英

如何訪問 SwiftUI 中的子視圖?

[英]How can I access the subviews in SwiftUI?

我正在嘗試我們的 SwiftUI 並想在 SwiftUI 組件的行上創建一個組件。 所以,這就是我想要做的:

創建一個擴展View的新視圖

struct CustomComponent: View {
    var title: String
    var body: some View {
        HStack {
            Image(systemName: "") // This would be updated through style
            Text(verbatim: title)
        }

    }
}

extension View {

    public func componentStyle<S>(_ style: S) -> some View where S : ComponentStyle {
        guard self is CustomComponent else {
            return AnyView(self)
        }

        return AnyView(
// Here I want to add the spacing attribute of the style to the HStack.
// Also I want to update the Image with the corresponding style's icon.
// If it's not possible here, please suggest alternate place.
            self
                .foregroundColor(style.tintColor)
                .frame(height: style.height)
        )
    }

}

public protocol ComponentStyle {
    var icon: String { get }
    var tintColor: Color { get }
    var spacing: CGFloat { get }
    var height: CGFloat { get }
}

struct ErrorStyle: ComponentStyle {
    var icon: String {
        return "xmark.octagon"
    }

    var tintColor: Color {
        return .red
    }

    var spacing: CGFloat {
        return 8
    }

    var height: CGFloat {
        return 24
    }
}

我怎樣才能實現以下目標:

  • 如何將樣式的間距屬性添加到 HStack?
  • 如何使用相應樣式的圖標更新圖像?

謝謝

您可以創建自定義EnvironmentKey

extension EnvironmentValues {
    private struct ComponentStyleKey: EnvironmentKey {
        static let defaultValue: ComponentStyle = ErrorStyle()
    }
    
    var componentStyle: ComponentStyle {
        get { self[ComponentStyleKey] }
        set { self[ComponentStyleKey] = newValue }
    }
}

並使用它來傳遞一些ComponentStyle作為@Environment變量:

struct ContentView: View {
    var body: some View {
        CustomComponent(title: "title")
            .componentStyle(ErrorStyle())
    }
}

struct CustomComponent: View {
    @Environment(\.componentStyle) private var style: ComponentStyle
    var title: String

    var body: some View {
        HStack(spacing: style.spacing) {
            Image(systemName: style.icon)
            Text(verbatim: title)
        }
    }
}

extension CustomComponent {
    func componentStyle<S>(_ style: S) -> some View where S: ComponentStyle {
        environment(\.componentStyle, style)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM