iOS Development

ios – Methods to apply unintended effects in a swiftui ViewBuilder

Spread the love


I’m making an attempt to render a easy Textual content() and apply an arbitrary variety of completely different kinds .
That is my code:

struct Cell {
    var content material: String
    var model: TextStyle
}

@ViewBuilder
func styledText(cell: Cell) -> some View {
    if (cell.model.comprises(TextStyle.rtl)) {
        Textual content(cell.content material)
            .body(maxWidth: .infinity, alignment: .main)
            .setting(.layoutDirection, .rightToLeft)
            .lineSpacing(10)
    } else if (cell.model.comprises(TextStyle.customFont)) {
        Textual content(cell.content material).font(.customized("MyFont", measurement: 19))
    } else if (cell.model.comprises(TextStyle.pinkColour)) {
        Textual content(cell.content material).foregroundStyle(Shade(UIColor.systemPink))
    } else {
        Textual content(cell.content material)
    }
}

You may see from the above that just one department can execute within the above perform. However in my app, a number of kinds could possibly be utilized (e.g. BOTH customFont and pinkColour). How do I obtain this?

What I attempted

@ViewBuilder
func styledText(cell: Cell) -> some View {
    var textual content = Textual content(cell.content material)
    if (cell.model.comprises(TextStyle.rtl)) {
        textual content = textual content
            .body(maxWidth: .infinity, alignment: .main)
            .setting(.layoutDirection, .rightToLeft)
            .lineSpacing(10)
    } else if (cell.model.comprises(TextStyle.customFont)) {
        textual content = textual content.font(.customized("MyFont", measurement: 19))
    } else if (cell.model.comprises(TextStyle.pinkColour)) {
        textual content = textual content.foregroundStyle(Shade(UIColor.systemPink))
    }
    textual content
}

So far as I perceive (I am new to Swift), each department should lead to a return worth so the above doesn’t work.

I additionally tried not utilizing @ViewBuilder in any respect, however I can not get my code to kind verify. I get errors equivalent to Can not assign worth of kind 'some View' (results of 'Self.font') to kind 'some View' (kind of 'textual content')

What am I lacking?

Leave a Reply

Your email address will not be published. Required fields are marked *