Regarding this insanity from Apple.
Here is perhaps the "clearest", simplest, way to do it:
First, you must correctly move the text.
Note this critical QA: https://stackoverflow.com/a/27066764/294884
class TidyTextField: UITextField {
@IBInspectable var leftImage: UIImage? = nil
@IBInspectable var leftPadding: CGFloat = 0
@IBInspectable var gapPadding: CGFloat = 0
private var textPadding: UIEdgeInsets {
let p: CGFloat = leftPadding + gapPadding + (leftView?.frame.width ?? 0)
return UIEdgeInsets(top: 0, left: p, bottom: 0, right: 5)
}
override open func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: textPadding)
}
override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: textPadding)
}
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: textPadding)
}
continuing, we now have to make and move the left image:
override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
var r = super.leftViewRect(forBounds: bounds)
r.origin.x += leftPadding
return r
}
override func layoutSubviews() {
super.layoutSubviews()
setup()
}
private func setup() {
if let image = leftImage {
if leftView != nil { return } // critical!
let im = UIImageView()
im.contentMode = .scaleAspectFit
im.image = image
leftViewMode = UITextField.ViewMode.always
leftView = im
} else {
leftViewMode = UITextField.ViewMode.never
leftView = nil
}
}
}
This seems to be about the clearest, most reliable way to do it.