swift - 如何访问 SwiftUI 中的 subview ?

标签 swift swiftui

我正在尝试我们的 SwiftUI 并想在 SwiftUI 组件的基础上创建一个组件。 所以,这就是我想要做的:

创建一个扩展 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
    }
}

我怎样才能实现以下目标:

  • 如何将样式的间距属性添加到 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)
    }
}

关于swift - 如何访问 SwiftUI 中的 subview ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66210554/

相关文章:

SwiftUI List 在底部添加空白

ios - 按钮覆盖显示在按钮文本、SwiftUI 上

ios - 如何告诉 SwiftUI View 绑定(bind)到多个嵌套的 ObservableObject

Swift CLAuthorizationStatus 总是 CLAuthorizationStatus.NotDetermined

swift - 如何以编程方式添加导航 Controller ,我正在快速使用 XIB 文件

Swift UIKit Combine - 处理发布者事件时如何重新加载表格 View ?

swiftui - 如何使用 SwiftUI 删除按钮的高亮显示?

swiftui-list - 喜欢带有 GroupedListStyle SwiftUI View 的LargeTitles

ios - 将闭包保存为变量理解

ios - 如何在SKShapeNode内移动SKNode但禁止子节点离开父节点?