How to get left padding on UITextField leftView image?

For Swift 3 Users

Here is what worked for me:

extension UITextField {

 /// set icon of 20x20 with left padding of 8px 
 func setLeftIcon(_ icon: UIImage) {

    let padding = 8
    let size = 20

    let outerView = UIView(frame: CGRect(x: 0, y: 0, width: size+padding, height: size) )
    let iconView  = UIImageView(frame: CGRect(x: padding, y: 0, width: size, height: size))
    iconView.image = icon
    outerView.addSubview(iconView)

    leftView = outerView
    leftViewMode = .always  
  }
}

test:

txOrigin.setLeftIcon(icon_location)

result:

enter image description here


For Swift 4.2 +

You can use this extension:

extension UITextField {
    func leftImage(_ image: UIImage?, imageWidth: CGFloat, padding: CGFloat) {
        let imageView = UIImageView(image: image)
        imageView.frame = CGRect(x: padding, y: 0, width: imageWidth, height: frame.height)
        imageView.contentMode = .center
        
        let containerView = UIView(frame: CGRect(x: 0, y: 0, width: imageWidth + 2 * padding, height: frame.height))
        containerView.addSubview(imageView)
        leftView = containerView
        leftViewMode = .always
    }
}