0

I have a UITextField where I want to set an icon image on the left side. Here is my code for it. Can anyone please point out my mistake?

override func layoutSubviews() {
    super.layoutSubviews()
    self.layer.cornerRadius = self.bounds.height/2
    self.layer.borderWidth = 2.0
    self.layer.borderColor = UIColor.white.cgColor

    self.leftViewMode = .always
    let iconImageView = UIImageView(frame: CGRect(x: 5, y: 5, width: self.bounds.height - 10, height: self.bounds.height - 10))
    iconImageView.image = UIImage(named: "email")
    let iconView = UIView()
    iconView.frame = iconImageView.bounds
    iconView.addSubview(iconImageView)
    self.leftView = iconView
    self.tintColor = .white
}
TylerP
  • 9,600
  • 4
  • 39
  • 43
Natasha
  • 6,651
  • 3
  • 36
  • 58

1 Answers1

0

Here is how you can create a custom field programmatically.
From this you can also get the idea for setting icon to textField.

class ViewController: UIViewController {

    ///Creating textField
    private let textField: UITextField = {
        let tf = UITextField()
        
        tf.leftViewMode = .always
        tf.borderStyle = .line
        let iconImageView = UIImageView()
        iconImageView.image = UIImage(named: "HomeSelected")
        iconImageView.contentMode = .scaleAspectFill
        
        
        let iconView = UIView()
        /// Settiing height iconView
        iconView.translatesAutoresizingMaskIntoConstraints = false
        iconView.heightAnchor.constraint(equalToConstant: 50).isActive = true
        iconView.widthAnchor.constraint(equalToConstant: 50).isActive = true
        
        iconView.addSubview(iconImageView)
        
        /// Applying constraints to iconImageView
        iconImageView.translatesAutoresizingMaskIntoConstraints = false
        iconImageView.topAnchor.constraint(equalTo: iconView.topAnchor, constant: 5).isActive = true
        iconImageView.leftAnchor.constraint(equalTo: iconView.leftAnchor, constant: 5).isActive = true
        iconImageView.bottomAnchor.constraint(equalTo: iconView.bottomAnchor, constant: -5).isActive = true
        
        ///Setting height of iconImageView
        iconImageView.heightAnchor.constraint(equalToConstant: 40).isActive = true
        iconImageView.widthAnchor.constraint(equalToConstant: 40).isActive = true

        
        tf.leftView = iconView
        // Setting Height of Textfield
        tf.translatesAutoresizingMaskIntoConstraints = false
        tf.heightAnchor.constraint(equalToConstant: 50).isActive = true
        return tf
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        view.addSubview(textField)
        ///Apply constraints to text Field.
    }


}

Result

TextFieldResult

Aafaq
  • 202
  • 1
  • 13