Ashh Ashh - 1 month ago 25
Swift Question

add icon in uitextfield - iOS Swift

I'm trying to add icon in textfield. This is how my UI looks now with code below

Im expecting my UI should look similar to this image

// creating view (holderView) to hold icon image(image) and add view to textField (txtEmail)

let holderView = UIView(frame: CGRect(x:0, y:0, width: 40, height: 40))

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))

let image = UIImage(named: "ic_lock_48pt")

imageView.image = image

holderView.backgroundColor = UIColor.lightGray

holderView.addSubview(imageView)

imageView.center = CGPoint(x: holderView.frame.size.width / 2, y: holderView.frame.size.height / 2)

txtEmail.leftView = holderView


(If im doing long process to fix this please let me know)

so I wanted to add constraints programatically to fix and below is the code

holderView.translatesAutoresizingMaskIntoConstraints = false

let leadingConstraint = NSLayoutConstraint(item: holderView, attribute: .leading, relatedBy: .equal, toItem: emailView, attribute: .leading, multiplier: 1, constant: 0)

let trailingConstraint = NSLayoutConstraint(item: holderView, attribute: .trailing, relatedBy: .equal, toItem: emailView, attribute: .trailing, multiplier: 0.12, constant: 0)

let topConstraint = NSLayoutConstraint(item: holderView, attribute: .top, relatedBy: .equal, toItem: emailView, attribute: .top, multiplier: 1, constant: 0)

let bottomConstraint = NSLayoutConstraint(item: holderView, attribute: .bottom, relatedBy: .equal, toItem: emailView, attribute: .bottom, multiplier: 1, constant: 0)


//I have txtEmail in another view (emailView)
//Error while running any of two lines of code below

emailView.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint]) //or
txtEmail.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint])


Kindly suugest me how to fix this

Joe Joe
Answer

Try his code:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    textfield.leftViewMode = UITextFieldViewMode.always
    let imageView = UIImageView(frame: CGRect(x: -1, y: 0, width: 30, height: 40))
    let image = UIImage(named: "q.png")
    imageView.backgroundColor = UIColor(white: 0.7, alpha: 0.6)
    imageView.image = image
    textfield.leftView = imageView

    textfield.layer.borderColor = UIColor(white: 0.7, alpha: 0.6).cgColor
    textfield.layer.borderWidth = 2

    imageView.layer.borderColor = UIColor(white: 0.7, alpha: 0.6).cgColor
    imageView.layer.borderWidth = 2

    textfield.layer.cornerRadius = 5
    textfield.layer.masksToBounds = true

 }

Note: You have to create an icon image similar to below image to achieve the effect.Its all about creating an icon and place it in a right position.hope this helps..

enter image description here

Output:

enter image description here