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?

1
  • 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. Commented Dec 24, 2022 at 12:52

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.