3

I've added a left view to my text field using the code below:

    usernameField.leftViewMode = UITextFieldViewMode.always
    passwordField.leftViewMode = UITextFieldViewMode.always

    let usernameImageView = UIImageView()
    let usernameImage = UIImage(named: "user icon grey.png")
    usernameImageView.image = usernameImage
    usernameField.leftView = usernameImageView

    let passwordImageView = UIImageView()
    let passwordImage = UIImage(named: "lock icon grey.png")
    passwordImageView.image = passwordImage
    passwordField.leftView = passwordImageView

This didn't work, I then added a UIDesignable, a very neat process that I took from this question below on StackOverflow. This means that I can see the icons in the storyboard, as can be seen below. However, this doesn't show up. Simulator Photo without text field icons Storyboard with the text field icons

Swift add icon/image in UITextField

Community
  • 1
  • 1
Jake Walker
  • 305
  • 2
  • 9

2 Answers2

6

The problem is with how you create the image view. You first create an empty image view which then has no size. You then assign the image to the image view but this does not automatically resize the image view.

There are two solutions.

  1. Tell the image view to resize itself after assigning the image.

    let usernameImageView = UIImageView()
    let usernameImage = UIImage(named: "user icon grey.png")
    usernameImageView.image = usernameImage
    usernameImageView.sizeToFit()
    
  2. Create the image view with the image. This is simpler approach.

    let usernameImage = UIImage(named: "user icon grey.png")
    let usernameImageView = UIImageView(image: usernameImage)
    
rmaddy
  • 314,917
  • 42
  • 532
  • 579
0

The problem is with your code. using this code now your left view in textField is working.

@IBOutlet weak var name: UITextField!
override func viewDidLoad() {
  super.viewDidLoad()
  usernameField.leftViewMode = .always
  let usernameImageView = UIImageView()
  usernameImageView.frame = CGRect(x: 0, y: 0, width: 25, height: 25)
  let usernameImage = (your image name)
  usernameImageView.image = usernameImage
  usernameField.leftView = usernameImageView