How to display a diff UI with AttributedStrings

140 Views Asked by At

I'm working on a feature that compares a new input to an old input. I'd like it to look like a git diff as seen in bitbucket or github, etc.

I currently have an array of characters with a prefix as to whether they were added or removed. Now I'm stuck at displaying each of those strings with a different background color while maintaining some normal sentence-like structure. The below code just makes a new Text() element on a new line, which isn't readable.

VStack {
    ForEach(diff.indices, id: \.self) { index in
        Text(diff[index]).foregroundColor(diff[index].hasPrefix("+add") ? .green : .black)
    }
}

People give examples of using "+" to string Text() elements together, but I can't within the ForEach.

Thoughts?

1

There are 1 best solutions below

0
rcobelli On

I would recommend abstracting out the ForEach then. While the Text element in SwiftUI doesn't allow for syntactic sugar like +=, you can still concatenate them together with + (reference).

You can achieve what you are looking for using this:

var body: some View {
    formattedText
}

var formattedText: Text {
    var output = Text("")

    diff.forEach { i in
        output = output + Text(i).foregroundColor(i.hasPrefix("+add") ? .green : .black)
        // TODO: check for a removal prefix and remove the prefix 
        // itself from the string so it isn't displayed
    }

    return output
}