uitextfieldswiftui

SwiftUI add image to left side of text field


I'm trying to get an SF Symbol on the left side of a text field in SwiftUI, but the methods used before SwiftUI don't really work. I thought this code would work, but it didn't. Also if anyone could help, how would I change the font and color of the text in the text field?

Here's an image of what I'm trying to accomplish: https://i.sstatic.net/Dud0M.png

TextField(textFieldDescription, text: 
                .constant(""))
                .padding(.all)
                .background(textFieldBackground)
                .cornerRadius(10)
                .leftViewMode = Image(systemName: "lock").always
                .leftViewMode = .always

Solution

  • Here's one implementation. Note that there is a bug, where if the initial text of the textfield is empty, the color and font setting will be ignored:

    HStack {
        Image(systemName: "lock")
        TextField("", text: .constant("typed text")).foregroundColor(Color.red).font(Font.custom("Papyrus", size: 16))
    }
    .padding()
    .overlay(RoundedRectangle(cornerRadius: 10).stroke(lineWidth: 2).foregroundColor(Color.black))