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

I have a text box:

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

This text box shows an input field with an expanded image. But I want a simple icon to the left of the input, how do I resize and resize the image?

+4
source share
2 answers

Use the attribute of the leftViewtext box and place there UIImageViewto place the image on the left side of the text box.

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

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

tf.leftViewMode = .always
+4
source

You can use property leftView UITextField

let textField : UITextField = UITextField()
textField.leftView = UIImageView(image: UIImage(named: "your_image"))
textField.leftViewMode = .always
+3
source

Source: https://habr.com/ru/post/1681880/


All Articles