read

When creating a custom view, it is common to init with a String, either with localization or not. This post will explore a few ways to init the custom view (largely depends on your requirement).

Take a simple TagView as an example.

struct TagView: View {
    let text: LocalizedStringKey

    var body: some View {
        Text(text)
            .padding()
            .background(
                RoundedRectangle(cornerRadius: 4)
                    .strokeBorder(.green, lineWidth: 1)
            )
    }
}

In the above, the view simply provide the LocalizedStringKey property. This supports localization as opposed to using String type.

Supporting both LocalizedStringKey & String

You have seen how Text provides different initializations supporting either types.

We can support similarly, with the following initializations.

struct TagView: View {
    let text: Text

    init(_ text: LocalizedStringKey) {
        self.text = Text(text)
    }

    @_disfavoredOverload
    init<S>(_ text: S) where S : StringProtocol {
        self.title = Text(text)
    }
}

The attribute @_disfavoredOverload is to ignore the init when overloaded (prioritize the init with LocalizedStringKey).

We also kind of cheated, changing the property to a full fledge Text type. But this is rather common eg. Label is made up of Text + Image. They are view representation anyway, so it is fine to provide in a custom view.

You can even init directly with a Text, giving call sites the power bold it, change the font, or whatever.

As said in the beginning, it depends on your requirement and how much you want to expose.


Image

@samwize

¯\_(ツ)_/¯

Back to Home