如何创建自定义修改器以在 SwiftUI 中操作自定义视图?

How to create custom Modifier to manipulate custom View in 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'
    }
}

问题

我怎样才能实现自定义 Modifier 的目标,它不仅可以修改 foregroundColorfont 等基本内容,还可以修改 title 等更具体的内容在所有符合特定协议的视图上?非常感谢您的帮助!

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

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

使用 Xcode 13.3

测试