Search code examples
iosimageuitextfieldcgrectleftview

CGRect function is not working while placing image in textfield


I am trying to set image inside the textfield , and for that i am creating an image view in code but when i am trying to adjust its width and height via CGRect(x:int, y:int, width:int, height:int) , its not being applied and the image size is still original. I ve seen so many tutorials for putting image in text field and all of them are using CGRect and its working for them, as size of image gets what they apply in CGRect, but not for me. Below is the code i m trying to use. Image is also attached. Textfield style is rounded (Default) and icon size is 50px. enter image here

UIViewController

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var email: UITextField!
override func viewDidLoad() {
    super.viewDidLoad()
    update()
    // Do any additional setup after loading the view.
}

func update() {
    email.leftViewMode = .always
    let imageview = UIImageView()
    let image = UIImage(named: "icon")
    imageview.image = image
    imageview.frame = CGRect(x: 15, y: 0, width: 50 , height: 50)
    email.leftView = imageview
}

}

Also, i ve tried to change 'Render as' to 'template' in image assets but its still not working.


Solution

  • Hey I’ve tried to do it programmatically and it works for me. Quickly drafted it on iPad playgrounds. Try this:

    class Test: UIViewController {
    
    let lable = UITextField()
    let image = UIImage()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        lable.frame = CGRect(x: 200, y: 200, width: 300 , height: 50)
        lable.backgroundColor = .black
        update()
        self.view.addSubview(lable)
    }
    
    func update() {
        lable.leftViewMode = .always
        let imageview = UIImageView()
        let image = UIImage(systemName: "icloud")
        imageview.image = image
        imageview.frame = CGRect(x: 15, y: 0, width: 50 , height: 50)
        lable.leftView = imageview
        self.view.addSubview(imageview)
    }
    

    }