How can I change the position of the leftView
in a UITextField
?
I have tried this, but the leftView
position does not change
UIView *view = [[UIView alloc]init];
[view setFrame:CGRectMake(10, 10, 15, 15)];
[view setBackgroundColor:[UIColor blackColor]];
[self.urlBar setLeftView:view];
[self.urlBar setLeftViewMode:UITextFieldViewModeAlways];
To change the position of the leftView
you need to create your own subclass of UITextField
and override the leftViewRectForBounds:
method to return a different frame.
The following code will give you a padding (displacement) of 20 from left.
@IBDesignable
class LeftImageTextField: UITextField {
let displacement: CGFloat = 20
required override public init(frame: CGRect) {
super.init(frame: frame)
sharedSetup()
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
sharedSetup()
}
func sharedSetup() {
self.leftViewMode = .always
self.leftView = UIImageView(image: UIImage(named: "myImage"))
}
override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
var textRect = super.leftViewRect(forBounds: bounds)
textRect.origin.x += displacement
return textRect
}
// placeholder position
override func textRect(forBounds bounds: CGRect) -> CGRect
{
var textRect = super.textRect(forBounds: bounds)
textRect.origin.x -= displacement
return textRect
}
// text position
override func editingRect(forBounds bounds: CGRect) -> CGRect
{
var textRect = super.editingRect(forBounds: bounds)
textRect.origin.x -= displacement
return textRect
}
override func placeholderRect(forBounds bounds: CGRect) -> CGRect
{
return bounds
}
/**
Changes to this parameter draw the border of `self` in the given width.
*/
@IBInspectable
var leftImage: UIImage? {
didSet {
self.leftView = UIImageView(image: leftImage)
}
}
}
Solution for iOS 13 on Swift 5:
let padding: CGFloat = 8
let outerView = UIView(frame: CGRect(x: 0, y: 0, width: padding * 2 + 23, height: 23))
let imageView = UIImageView(frame: CGRect(x: padding, y: 0, width: 23, height: 23))
imageView.image = image
outerView.addSubview(imageView)
leftView = outerView // Or rightView = outerView
leftViewMode = .always // Or rightViewMode = .always
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With