Gunja Patel Gunja Patel - 9 days ago 5
Swift Question

Swift UITextField icon position set

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 thisImage is close to textfield border

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 enter image description here

I want o/p like this

enter image description here

Answer

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.