swift 5 add image to uitextfield code example
Example: uitextfield add image swift 5
Useing example:
let textView = BaseTextField()
textView.rightImage = "magnifyingglass"
class BaseTextField: UITextField {
var setHPad: UIEdgeInsets = { return UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8 ) }()
override open func textRect( forBounds bounds: CGRect ) -> CGRect {
return bounds.inset( by: self.setHPad )
}
override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: self.setHPad )
}
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: self.setHPad )
}
@IBInspectable open var rightImage:String? {
didSet {
if (rightImage != nil) {
self.applyImage(rightImage!, false)
self.setHPad = { return UIEdgeInsets( top: 0, left: 8, bottom: 0, right: 30 ) }()
}
}
}
@IBInspectable open var leftImage:String? {
didSet {
if (leftImage != nil) {
self.applyImage(leftImage!, true)
self.setHPad = { return UIEdgeInsets( top: 0, left: 30, bottom: 0, right: 8 ) }()
}
}
}
fileprivate func applyImage(_ image: String, _ isLeftImage: Bool) {
let imageView = UIImageView()
imageView.image = UIImage( systemName: image )
imageView.tintColor = UIColor( named: K.EpColors.black )
imageView.clipsToBounds = true
let viewHolder = UIView()
viewHolder.clipsToBounds = true
viewHolder.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
viewHolder.translatesAutoresizingMaskIntoConstraints = false
let viewsDictionary = [
"imageHolder": viewHolder,
"image":imageView
]
let metrics = [
"default": 8,
"none": 0
]
viewHolder.addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "H:|-(default)-[image]-(default)-|",
options: [],
metrics: metrics,
views: viewsDictionary))
viewHolder.addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "V:|-(default)-[image]-(default)-|",
options: [],
metrics: metrics,
views: viewsDictionary))
self.addSubview(viewHolder)
self.clipsToBounds = true
let horizontalConstraint: String = isLeftImage ? "H:|-(none)-[imageHolder]-(>=default)-|" : "H:|-(>=default)-[imageHolder]-(none)-|"
self.addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: horizontalConstraint,
options: [],
metrics: metrics,
views: viewsDictionary))
self.addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "V:|-(none)-[imageHolder]-(none)-|",
options: [],
metrics: metrics,
views: viewsDictionary))
}
}