0

I'm currently developing an application using SwiftUI.

I prepared a base character String and a TextField, and if the character String entered in the TextField is included in the base character String, I want to change the color of the target characters.

So far, I have implemented changing the input character String to a different one, but I can not change the color of the character.

Is there a way to do this when using SwiftUI?


In the case of the code below, if I enter apple, the apple part in the base String will change to a different String( replaceString ), but I want to change only the text color while keeping the same String.

Here is the code:

import SwiftUI

struct CheckWords: View {

    @State var baseString = "I like apples but don't like oranges"
    @State var word = "apple"

    var body: some View {
        VStack{
            HStack{
                Text("redWord")
                TextField("redWord",text:self.$word)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .autocapitalization(.none)
            }
            .padding()

            Text(self.baseString)
                .font(.title)
                .padding()

            Divider()

            Text("result:")
                .padding()

            Text(self.changeString())
                .font(.title)
                .padding()
        }
    }

    func changeString() -> String{
        if let range = baseString.range(of: word) {
            let replaceString = baseString.replacingCharacters(in: range, with: "replaceString")
            return replaceString
        }else{
            return self.baseString
        }
    }
}

Xcode: Version 12.3

iOS: 14.0

Tio
  • 944
  • 3
  • 15
  • 35
  • 1
    Does this answer your question https://stackoverflow.com/a/59531328/12299030? – Asperi Jun 03 '21 at 15:01
  • 1
    @Asperi Sorry, I thought you comment gets +1 for suggesting the same link. – vadian Jun 03 '21 at 15:04
  • @Asperi , @vadian, Thank you for your support, combining multiple Text objects together(`Text() + Text()`) seems to be useful. For example, if I enter `apple` in the `TextField`, Is there a way to divide it into three `Text()`: `I like`,`apple`, `s but don't like oranges` ? – Tio Jun 03 '21 at 15:36

0 Answers0