如何设置在 UITextField 中添加的图标的位置?

问题描述:

电子邮件图标和占位符文本相互拥抱.

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)

谢谢!

无需子类化的最简单方法是让 EmailIcon 宽度比 emailIconImage 宽度多 10pts.然后根据需要将EmailIcon 的contentMode 设置为center 或right.这是obj C 中的代码,希望你能很快搞清楚:

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;