Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: Multi colours text in TextField

Tags:

ios

swift

swiftui

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)
like image 694
Shahzaib Avatar asked Oct 19 '25 12:10

Shahzaib


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

like image 64
ios coder Avatar answered Oct 21 '25 00:10

ios coder