4

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?

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
sakoaskoaso
  • 347
  • 4
  • 17
  • See this question: [Swift add icon/image in UITextField](https://stackoverflow.com/questions/27903500/swift-add-icon-image-in-uitextfield) – Anh Pham Jul 20 '17 at 14:07

2 Answers2

6

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
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
3

You can use leftView property of UITextField

let textField : UITextField = UITextField()
textField.leftView = UIImageView(image: UIImage(named: "your_image"))
textField.leftViewMode = .always
kamwysoc
  • 6,709
  • 2
  • 34
  • 48
  • Thanks for your heuristic answer,but i think you forgot about `tf.leftViewMode = .always`,my code didn't work without it. – sakoaskoaso Jul 20 '17 at 14:08