Add Icon in UITextField using
var leftImageView = UIImageView()
leftImageView.image = leftImage
textField.leftView = leftImageView
textField.leftViewMode = UITextFieldViewMode.Always
leftImageView.frame = CGRectMake(15, 10, 15, 20)
textField.addSubview(leftImageView)
o/p for this
I found solution like remove this code from above code
textField.leftView = leftImageView
It give icon alignment proper but whenever start editing text field text on icon like this
I want o/p like this
First of all, you should definitely not add the image as a subview to the label. It's enough to set the leftView
property.
textField.addSubview(leftImageView) // Delete this line
Secondly, any x or y offsets that you apply to the left view's frame are ignored. The text field will only care about the view's size. If you want to add padding around the image, one option is to use a container view and position the image view inside of it.
let leftImageView = UIImageView()
leftImageView.image = leftImage
let leftView = UIView()
leftView.addSubview(leftImageView)
leftView.frame = CGRectMake(0, 0, 30, 20)
leftImageView.frame = CGRectMake(0, 0, 15, 20)
textField.leftView = leftView
Another option would be to subclass UITextField
and override leftViewRectForBounds
.
Referring @hennes syntax , there are some syntax missing in swift like CGRect syntax is changed and userNameTextField.leftViewMode = .always
is missing
With swift syntax this worked for me :
let leftImageView = UIImageView()
leftImageView.image = UIImage(named: "email")
let leftView = UIView()
leftView.addSubview(leftImageView)
leftView.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
leftImageView.frame = CGRect(x: 10, y: 10, width: 20, height: 20)
userNameTextField.leftViewMode = .always
userNameTextField.leftView = leftView
Try this. May be help you.
var padding: Float = 20
var envelopeView: UIImageView = UIImageView(frame: CGRectMake(padding, 0, 30, 30))
envelopeView.image = UIImage.imageNamed("comment-128.png")
envelopeView.contentMode = UIViewContentModeScaleAspectFit
var viewLeft: UIView = UIView(frame: CGRectMake(padding, 0, 30, 30))
viewLeft.addSubview(envelopeView)
textField.leftView.setFrame(envelopeView.frame)
textField.leftView = viewLeft
textField.leftViewMode = UITextFieldViewModeAlways
var viewRight: UIView = UIView(frame: CGRectMake(textField.frame.size.width - (textField.frame.size.width + 30 + padding), 0, 30, 30))
viewRight.addSubview(envelopeView)
textField.rightView.setFrame(envelopeView.frame)
textField.rightView = viewRight
textField.rightViewMode = UITextFieldViewModeAlways
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With