Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change UITextField leftview frame

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];
like image 783
Mojtaba Avatar asked Mar 11 '14 12:03

Mojtaba


3 Answers

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.

like image 112
Wain Avatar answered Oct 14 '22 09:10

Wain


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)
    }
}
}
like image 33
K.K Avatar answered Oct 14 '22 08:10

K.K


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
like image 27
Vergiliy Avatar answered Oct 14 '22 07:10

Vergiliy