如何设置在 UITextField 中添加的图标的位置? [英] How to set position of an icon added in UITextField?

查看:32
本文介绍了如何设置在 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;

这篇关于如何设置在 UITextField 中添加的图标的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆