如何创建自定义 Modifier 来操作 SwiftUI 中的自定义 View?

chr*_*epe 4 generics view modifier swift swiftui

语境

您好,我目前经常SwiftUI使用Modifiers. 我有这个基本设置:


代码

// This TitleView Protocol should be adapted by all SwiftUI Views containing a Title.
protocol TitleView: View {
    var title: String { get set }
}

// This is one of many Views containing a Title, therefore it conforms to the TitleView Protocol.
struct SomeTitleView: TitleView {
    var title: String = "Hello World";

    var body: some View {
        Text(title)
    }
}

// This Extension adds the setTitle Modifier to all Views conforming to TitleView.
extension View where View: TitleView {
    func setTitle(_ title: String) -> some View {
        self.modifier(CRStyleModifier(title: title))
    }
}

// This ViewModifier is supposed to manipulate the Title Property inside Views conforming to TitleView. 
// However, I am not sure how to accomplish it.
struct TextModifier: ViewModifier {
    let title: String
    
    @ViewBuilder func body<Content: TitleView>(content: Content) -> some View {
        content 
        // How can I update the Title Property of the Content?
        // Once I make the body Method generic, I get this error message -> Type 'CRStyleModifier' does not conform to protocol 'ViewModifier'
    }
}
Run Code Online (Sandbox Code Playgroud)

问题

我怎样才能实现我的目标,即拥有一个自定义Modifier,不仅可以修改基本的东西foregroundColorfont而且还可以修改更具体的东西,比如title符合特定协议的所有视图?非常感谢你的帮助!

Asp*_*eri 5

自定义修饰符是可能的,但在这种情况下不需要,因为会引入不必要的复杂性,相反,您的扩展可以看起来像

extension View where Self: TitleView {
    func setTitle(_ title: String) -> some View {
        var newView = self
        newView.title = title
        return newView
    }
}
Run Code Online (Sandbox Code Playgroud)

使用 Xcode 13.3 进行测试