Search code examples
iosiphonexcodeswiftuimodifier

SwiftUI how to apply text modifier to custom view with Text in it


I create a custom text component, which wraps the Text in it.

struct ScrollText:View{
    let text: String
    var body: some View {
        Text("\(text) the logic is like that")
    }
}

Then I want this view can use the modifier of Text such as .font, .fontWeight, .tracking

ScrollText(text:"abcdefg")
     .font(.body)
     .tracking(-0.3)

But I found that in iOS 15 only .font can work. What can I do to make it work as the normal Text component?


Solution

  • Why text modifiers can not be used in my custom view is that in iOS 15, these modifiers only works with type "Text", but our view return "some View" instead.

    So it can be done by using

    extension Text{
        func addaPlus(activate:Bool)->some View{
            return ScrollText(text: self, activate: activate)
        }
    }
    

    In this function, self means Text, and instead of passing the string to the view we pass the Text and place it in the last position, which transforms the Text to some View.

    By the way, I don't know how to read and modify the string inside the text by doing this.

     Text(longText)
             .tracking(-0.3)
             .addaPlus(activate: activate)
    

    But if you can return Text instead of some View, you can still use Text-only modifiers below this one.