Search code examples
iosswiftswift2paddingtextfield

Padding before TextField Icon


I got the way to apply an icon just before the textfield starts programmatically but the main concern was that to apply padding just before the icon.

As it is just touching the border of the textfield.

I program it like below:

override func viewWillAppear(animated: Bool) {

    // Email Icon on left of email Text Field
    let imageView1 = UIImageView()
    let image1 = UIImage(named: "Message.png")
    imageView1.image = image1
    imageView1.frame = CGRectMake(100, 0, 10, 10)
    emailTextField.leftView = imageView1
    emailTextField.leftViewMode = UITextFieldViewMode.Always

    // Password Icon on left of pass Text Field
    let imageView2 = UIImageView()
    let image2 = UIImage(named: "Lock.png")
    imageView2.image = image2
    imageView2.frame = CGRectMake(100, 0, 10, 10)
    passwordTextField.leftView = imageView2
    passwordTextField.leftViewMode = UITextFieldViewMode.Always

}

But all the way space between the border and the icon is very less.

Is there any way to make a padding between them?

Please let me know if there is any way.


Solution

    1. Try creating a UIView(say contentView) and a UIImageView(say leftImage)
    2. Set leftImage frame as it is aligned 10 points away from contenView's x(i.e) if contentView's frame is (0, 0, 25, 20) then set leftImage's frame as (10, 0, 15, 20)

    3. Then add leftImage as subview to contentView

    4. Now it's simple add contentView as leftView of textfield.

      let leftImage = UIImageView()
      
      let image1 = UIImage(named: "Key")
      leftImage.image = image1
      
      let contentView = UIView()
      contentView.addSubview(leftImage)
      
      contentView.frame = CGRectMake(0, 0, 25, 20)
      leftImage.frame = CGRectMake(10, 0, 25, 20)
      
      passwordTextField.leftView = contentView
      passwordTextField.leftViewMode = UITextFieldViewMode.Always
      

      Previops output:

      enter image description here

      Final Output:

      enter image description here