I created an @IBDesignable to allow developers to add an image to UITextFields on the Storyboard. You just have to add this file to your project:
Then add a UITextField to your view and set the custom class name for it:
You now have 3 properties open for you to add an image, padding and color. Color affects the image and placeholder text so they match. Note: The color of the image won't take effect until you run your project.
At runtime the color of the image will change:
@IBDesignable
class DesignableUITextField: UITextField {
// Provides left padding for images
override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
var textRect = super.leftViewRect(forBounds: bounds)
textRect.origin.x += leftPadding
return textRect
}
@IBInspectable var leftImage: UIImage? {
didSet {
updateView()
}
}
@IBInspectable var leftPadding: CGFloat = 0
@IBInspectable var color: UIColor = UIColor.lightGray {
didSet {
updateView()
}
}
func updateView() {
if let image = leftImage {
leftViewMode = UITextFieldViewMode.always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
imageView.image = image
// Note: In order for your image to use the tint color, you have to select
// the image in the Assets.xcassets and change the "Render As" property to
// "Template Image".
imageView.tintColor = color
leftView = imageView
} else {
leftViewMode = UITextFieldViewMode.never
leftView = nil
}
// Placeholder text color
attributedPlaceholder = NSAttributedString(string:
placeholder != nil ?
placeholder! : "",
attributes:[NSForegroundColorAttributeName: color])
}
}
Then add a UITextField to your view and set the custom class name for it:
You now have 3 properties open for you to add an image, padding and color. Color affects the image and placeholder text so they match. Note: The color of the image won't take effect until you run your project.
At runtime the color of the image will change:



















































