Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: how to create an image on the left side of a text field?

Tags:

ios

swift

I have got a text field:

let usn_text_field: UITextField = {
        let tf = UITextField()
        tf.placeholder = "Username"
        tf.translatesAutoresizingMaskIntoConstraints = false
        tf.background = #imageLiteral(resourceName: "usericon2")
        return tf
    }()

This textfield shows an input field with an image expanded. But I want a simple icon on the left of the input, how can i resize and reposition the image?

like image 823
sakoaskoaso Avatar asked Jan 30 '23 23:01

sakoaskoaso


1 Answers

Use the leftView attribute of the text field and put a UIImageView there to place an image to the left side of your text field.

tf.leftView = UIImageView(image: #imageLiteral(resourceName: "usericon2"))

If you want to show it always, change the leftViewMode property of the text field:

tf.leftViewMode = .always
like image 138
Tamás Sengel Avatar answered Feb 05 '23 14:02

Tamás Sengel