0

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?

tim_d
  • 133
  • 2
  • 11
  • Once you add modifiers a Text is no longer a Text, it is a more complex “some View”, you can try “highlighting” if you want it to stay a string you have to treat it as such. – lorem ipsum Dec 24 '22 at 12:52

1 Answers1

1

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
}
rcobelli
  • 199
  • 1
  • 2
  • 14