SwiftUI: Multi colours text in TextField

Viewed 467

I want to change two different colours for the text in TextField. For first word, colour is dark-grey & for second word, colour is light-grey. Is it possible?

TextField("Dumble Dore!", text: $username)
1 Answers

There is an other way using just SwiftUI and what we have in hand to work with:

Xcode: Version 12.5.1 (12E507)

struct ContentView: View {
    
    @State private var string: String = "Dumble Dore!"
    
    var body: some View {
        
        CustomTextFieldView(titleKey: "Enter your text here ...", dropIndex: 7, string: $string)
        
    }
    
}




struct CustomTextFieldView: View {
    
    let titleKey: LocalizedStringKey
    let dropIndex: Int
    @Binding var string: String
    
    var body: some View {
        
        HStack(spacing: 0.0) {
            
            Text(string.dropLast((string.count >= dropIndex) ? (string.count - dropIndex) : 0)).foregroundColor(Color(UIColor.darkGray)).lineLimit(1)
            
            Text(string.dropFirst(dropIndex)).foregroundColor(Color(UIColor.lightGray)).lineLimit(1)
            
            Spacer()
        }
        .overlay(TextField(titleKey, text: $string).foregroundColor(.clear), alignment: .topLeading)
        
    }
    
}

enter image description here

Related