简体   繁体   English

如何访问 SwiftUI 中的子视图?

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

I am trying our SwiftUI and want to create a component on the lines of SwiftUI's components.我正在尝试我们的 SwiftUI 并想在 SwiftUI 组件的行上创建一个组件。 So, here is what I am trying to do:所以,这就是我想要做的:

Create a new view extending View创建一个扩展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
    }
}

How can I achieve the following:我怎样才能实现以下目标:

  • How can I add the spacing attribute of the style to the HStack?如何将样式的间距属性添加到 HStack?
  • How can I update the Image with the corresponding style's icon?如何使用相应样式的图标更新图像?

Thanks谢谢

You can create a custom EnvironmentKey :您可以创建自定义EnvironmentKey

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

and use it to pass some ComponentStyle as an @Environment variable:并使用它来传递一些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