0

I am trying to add icon inside the Textfield. Here, I am using multiple textfield with separate icons, I need to create subclass for adding left icon.

Here below my code for single textfield

var imageView = UIImageView();
var image = UIImage(named: "user-icon.png");
imageView.image = image;
imageView.frame = CGRectMake(100, 0, 20, 19);
usernameTextField.leftView = imageView;
usernameTextField.leftViewMode = UITextFieldViewMode.Always 

1 Answers1

4

Try this One is Working (Swift 4 Code)

extension UITextField{

    func setLeftImage(imageName:String) {

        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        imageView.image = UIImage(named: imageName)
        self.leftView = imageView;
        self.leftViewMode = .always
    }
}

Use Like this :

YourtextField.setLeftImage(imageName: "image_name")
Nikunj Kumbhani
  • 3,758
  • 2
  • 26
  • 51
  • i am sorry I am looking subclass for this. –  Aug 25 '18 at 11:58
  • @ApplePrime You can give separate icons name for each text field by using this one. – Nikunj Kumbhani Aug 25 '18 at 12:02
  • Hi, Could you please le me know why we are using button for this, can able to use UIView here? @Nikunj Kumbhani –  Aug 25 '18 at 12:19
  • @ApplePrime Yes you can add either image view or UIView whatever you want. Check Updated answer is with UIImageView. – Nikunj Kumbhani Aug 25 '18 at 12:32
  • icon sizes not sitting properly, I am doing universal application. I am getting bit spaces from left to icon and not much spaces between icon and placeholder. @Nikunj Kumbhani –  Aug 25 '18 at 12:44
  • @ApplePrime Add this Class into Project and assign that to your text field. https://stackoverflow.com/a/27066764/10150796 – Nikunj Kumbhani Aug 25 '18 at 13:07