如何设置在UITextField中添加图标的位置?
电子邮件图标和占位符文本互相拥抱。
我想在它们之间增加一些空间。
以下是我用来创build这些字段的代码。
// 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)
谢谢!
最简单的做法是不给子类创buildEmailIcon宽度,比emailIconImage宽度多10pts 。 然后根据你的需要设置EmailIcon的contentMode为中心或正确的。下面是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;
您可以从其图层更改位置:
txtemail.layer.position = CGPointMake(30, 30)
子类UITextField并实现以下方法将占位符文本置于所需的位置 –
placeholderRectForBounds: