2

I would like to add icon/image in UITextfield .The Icon/Image should be left to placeholder.I tried this coding but it is not showing icon/image inside the textfield .

var imageView = UIImageView();

var image = UIImage(named: "usericon.png");

imageView.image = image;

username.leftView = imageView;

username.leftViewMode = UITextFieldViewMode.Always
Gayathri
  • 163
  • 2
  • 2
  • 10
  • Why is it not working? Compilation error? Undesired/unexpected result? Runtime exception? – Antonio Feb 10 '15 at 11:44
  • It is not showing any error.But,I don't know why this code doesn't work – Gayathri Feb 10 '15 at 11:47
  • 1
    You should describe in your question what's wrong with your code, what's actually not working - no image shown, image shown in wrong place, etc. Also give some info about what `username` is. Please update the question and do **not** add as comment – Antonio Feb 10 '15 at 11:53
  • I want to design username textfield with icon using swift.I have used these codes but it is not showing icon inside the UITextfield. – Gayathri Feb 10 '15 at 11:56
  • You can also try looking at a similar question here for answers: http://stackoverflow.com/questions/27903500/swift-add-icon-image-in-uitextfield/41151566#41151566 – Mark Moeykens Feb 03 '17 at 01:25
  • try this library in swift 3 https://github.com/Sahilberi/ImageTextField – Sahil May 19 '17 at 10:59

2 Answers2

9

I think you forgot to add this code:

imageView.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
view.addSubview(imageView)

Image will show if u use this code.

May be this will help you.

Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
4

And In order to leave a space between the icon and the text

let imageView = UIImageView();
let image = UIImage(named: "icon_calendar");
imageView.image = image;
imageView.frame = CGRect(x: 10, y: 10, width: 20, height: 20)
textfield.addSubview(imageView)
let leftView = UIView.init(frame: CGRectMake(10, 0, 30, 30))
textfield.leftView = leftView;
textfield.leftViewMode = UITextFieldViewMode.Always
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Iman
  • 1,097
  • 2
  • 11
  • 19