如何设置的UITextField添加一个图标的位置?(How to set position of

2019-10-23 05:10发布

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

我想他们之间添加一些空间。

下面是我使用创建这些字段的代码。

// 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)

谢谢!

Answer 1:

要做到这一点没有子最简单的办法就是给EmailIcon 10pts超过emailIconImage宽度宽度 。 然后设置EmailIcon的contentMode到中心或根据您的need.Here 是OBJ C中的代码,希望你能弄清楚在迅速:

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;


Answer 2:

你可以改变其层的位置:

 txtemail.layer.position = CGPointMake(30, 30)


Answer 3:

子类的UITextField并实现下面的方法放置在您希望的位置占位符文本 -

placeholderRectForBounds:


文章来源: How to set position of an icon added in UITextField?