Sahil has a great answer and I wanted to take that and expand it into an @IBDesignable so developers can add images to their UITextFields on the Storyboard.
Swift 4.2
import UIKit
@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 = UITextField.ViewMode.always
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
imageView.contentMode = .scaleAspectFit
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 = UITextField.ViewMode.never
leftView = nil
}
// Placeholder text color
attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: color])
}
}
What is happening here?
This designable allows you to:
- Set an image on the left
- Add padding between the left edge of the UITextField and the image
- Set a color so the image and the Placeholder text matches
Notes
- For image color to change you have to follow that note in the comment in the code
- The image color will not change in the Storyboard. You have to run the project to see the color in the Simulator/device.
Designable in the Storyboard
At Runtime
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…