Adding Icons To UITextField

I promise to keep this on short .

I’m really having a good time as I continue learning sweet. Progress on my attempt to create an ‘Instagram clone’ is pretty good. Source code is available on Github.

All was going well until I tried adding icons to UITextField but it only lead to frustrations. So I thought I’d share how I got past this. By the end of this blog you should be able to add images you your TextFields


So let’s get started.

I’m assuming you have created your outlets from the storyboard to the related ViewController.

1. Define the ImageView:
let imageView = UIImageView();
let imageEmail = UIImage(named: "ic_email.png");
imageView.image = imageEmail;

2. Set up the frame for the image view:

imageViewEmail.frame = CGRect(x: 5, y: 5, width: 20, height: 20)


4. Setting padding: 

If you look at the above image, the icons seem to appear above the text. To fix this, you need padding to the textfield.

let paddingView = UIView(frame: CGRectMake(0, 0, 25, self.emailTextField.frame.height))
emailTextField.leftView = paddingView

This will add some space to the left of the text.


Complete Code

Happy coding.

(Visited 1,161 times, 1 visits today)

Leave a comment

Your email address will not be published. Required fields are marked *