0

I have a section of text where I am using .replacingOccurrences to display the users' answer within the question sentence:

           Text((question.text)
                .replacingOccurrences(of: "_____", with:
                    question.answers[question.userAnswer]
                ))
                .font(Font.custom("ClearSans-Bold", size: 18))
                .foregroundColor(.black )
                .padding(.bottom, 20)
                .multilineTextAlignment(.center)

I want the users' answer question.answers[question.userAnswer] to be a different colour (red/green) to the main body of the text (similar to attached image) however I'm new to SwiftUI so not sure how to add this in.

Image 1

ellxrr
  • 1
  • 1
  • 1
    Does this answer your question? [How to use Attributed String in SwiftUI](https://stackoverflow.com/questions/59531122/how-to-use-attributed-string-in-swiftui) – pawello2222 Aug 29 '20 at 20:58
  • You can join `Text` with different modifiers. For example you could have `Text("Hello").foregroundColor(.red) + Text("World").foregroundColor(.blue)`. – George Aug 29 '20 at 21:17

1 Answers1

0

Here's an extension for String that does pretty much what you want:

extension String {
    func replacingOccurrences(of: String, with: [Text]) -> Text {
        return self.components(separatedBy: of).enumerated().map({(i, s) in
            return i < with.count ? Text(s) + with[i] : Text(s)
        }).reduce(Text(""), { (r, t) in
            return r + t
        })
    }
}

It uses concatenation of Text elements as George_E suggested. You can use it like this:

struct ContentView: View {

    let question: String = "The witch found the concoction extremely _____. _____ makes better ones."

    let answers: [String] = ["nauseate", "A friend of her's"]

    var body: some View {
        question.replacingOccurrences(of: "_____", with: self.answers.map({s in Text(s).foregroundColor(.red)})).foregroundColor(.secondary)
    }
}

Result:

enter image description here

You may want to add some extra code for handling cases where the number of answers does not match the occurrences of _____.

theMomax
  • 919
  • 7
  • 8