问题
The email icon and placeholder text are hugging each other.
I want to add some space between them.
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!
回答1:
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;
回答2:
you can change the position from its layer:
txtemail.layer.position = CGPointMake(30, 30)
回答3:
Subclass UITextField and implement the following method to place the placeholder text in a position that you want -
placeholderRectForBounds:
来源:https://stackoverflow.com/questions/30500313/how-to-set-position-of-an-icon-added-in-uitextfield