【问题标题】:How to set position of an icon added in UITextField?如何设置在 UITextField 中添加的图标的位置?
【发布时间】:2015-08-10 14:13:24
【问题描述】:

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

我想在它们之间添加一些空间。

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

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

谢谢!

【问题讨论】:

标签: ios swift uitextfield uitextview


【解决方案1】:

不使用子类化的最简单方法是让 EmailIcon 宽度比 emailIconImage 宽度大 10 个百分点。然后根据你的需要设置EmailIcon的contentMode为center或right。这是obj C中的代码希望你能在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】:

    你可以从它的层改变位置:

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

    【讨论】:

      【解决方案3】:

      子类 UITextField 并实现以下方法以将占位符文本放置在您想要的位置 -

      placeholderRectForBounds:
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-16
        • 1970-01-01
        • 1970-01-01
        • 2016-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多