1

The email icon and placeholder text are hugging each other.

I want to add some space between them.

enter image description here

Below is the code I am using to create these fields.

// view for fields background
var view = UIView(frame: CGRectMake(35, 300, 300, 90));
view.backgroundColor = UIColor.whiteColor();
view.layer.cornerRadius = 5.0

// email text field
var email = UITextField(frame: CGRectMake(0, 0, 300, 50));
email.backgroundColor = UIColor.whiteColor();

var emailIcon = UIImageView();

var emailIconImage = UIImage(named: "email_icon.png");

emailIcon.image = emailIconImage;

email.leftView = emailIcon;

email.leftViewMode = UITextFieldViewMode.Always

email.layer.cornerRadius=5.0;

email.attributedPlaceholder = NSAttributedString(string:"E-mail",
    attributes:[NSForegroundColorAttributeName: UIColor.grayColor()])

emailIcon.frame = CGRect(x: 30, y: 15, width: 30, height: 20)

view.addSubview(emailIcon)

Thanks!

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Chetan Bhopal
  • 436
  • 4
  • 12
  • possible duplicate of [Text inset for UITextField?](http://stackoverflow.com/questions/2694411/text-inset-for-uitextfield) – Larme May 28 '15 at 08:57

3 Answers3

5

Easiest way to do this without subclassing is to give EmailIcon width 10pts more than the emailIconImage width. And then set contentMode of EmailIcon to centre or right according to your need.Here is the code in obj C hope you'll figure it out in swift:

EmailIcon = [[UIImageView alloc] initWithImage: emailIconImage];
EmailIcon.frame = CGRectMake(0.0, 0.0, EmailIcon.image.size.width+10.0, EmailIcon.image.size.height);
EmailIcon.contentMode = UIViewContentModeCenter;  //Or UIViewContentModeRight

textField.leftView = EmailIcon;
textField.leftViewMode = UITextFieldViewModeAlways;
0

you can change the position from its layer:

 txtemail.layer.position = CGPointMake(30, 30)
Özgür Ersil
  • 6,909
  • 3
  • 19
  • 29
0

Subclass UITextField and implement the following method to place the placeholder text in a position that you want -

placeholderRectForBounds:
Tushar
  • 3,022
  • 2
  • 26
  • 26