Search code examples
iosimageviewuitextfieldiconsleftview

Size of image inside textfield is not resizing


I have a custom text field and i want to place image on its left side, but when ever i am running the app, the size of image is not adjusting , i.e its full scale and not taking the width and height being provided. The code and pictures are attached

ViewController class:(In which text field is present) import UIKit

class Signup2ViewController: UIViewController {

  @IBOutlet weak var Email: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    Email.leftViewMode = .always
    let imageview = UIImageView()
    imageview.frame = CGRect(x: 0, y: 0, width: 5.0, height: 5.0)
    view.addSubview(imageview)
    let icon = UIImage(named: "c.png")
    imageview.image = icon
    Email.leftView = imageview


    // Do any additional setup after loading the view.
}

}

image of app


Solution

  • To set the frame for your imageView you need to subclass UITextField and override leftViewRect(forBounds:). The code below will result in a 20x20 view offset 10 points from the left and centered vertically.

    class AwesomeTextField: UITextField {
    
        override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
            let leftViewHeight: CGFloat = 20
            let y = bounds.size.height / 2 - leftViewHeight / 2
            return .init(x: 10, y: y, width: leftViewHeight, height: leftViewHeight)
        }
    }
    

    To add an imageView to the textField you would do this:

    class ViewController: UIViewController {
    
        @IBOutlet weak var textField: AwesomeTextField!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let imageView = UIImageView()
            imageView.image = UIImage(named: "c")
            textField.leftView = imageView
            textField.leftViewMode = .always
        }
    }
    

    Make sure you set the appropriate class name for the textField in the identity inspector of your storyboard.