Alper
Alper

Reputation: 1445

Adding image to the TextField

im trying to add an icon to my username textfield, somehow I added the icon but I cant add any padding to it.

What I mean is, I want it to look like this: enter image description here

And what I get is this: enter image description here

let usernameTextField: UITextField = {
        let tf = UITextField()


        let imageView = UIImageView()

        let image = UIImage(named: "user-icon")

        imageView.image = image
        imageView.frame = CGRect(x: 0, y: 0, width: 10, height: 15)
        tf.leftViewMode = UITextFieldViewMode.always
        tf.leftView = imageView
        tf.addSubview(imageView)


        var placeholder = NSMutableAttributedString(string: "username", attributes: [NSForegroundColorAttributeName: UIColor.lightGray])
        tf.attributedPlaceholder = placeholder
        tf.backgroundColor = UIColor.rgb(red: 34, green: 34, blue: 34)
        tf.borderStyle = .roundedRect
        tf.font = UIFont.systemFont(ofSize: 14)
        tf.layer.cornerRadius = 25
        tf.textColor = .white
        tf.layer.borderWidth = 1
        tf.layer.borderColor = UIColor(white: 1, alpha: 0.1).cgColor
        tf.layer.masksToBounds = true
        return tf
    }()

And this is my code block. Even if I change the x and y values it doesnt event move any pixels.

Upvotes: 1

Views: 2534

Answers (1)

Bilal
Bilal

Reputation: 19156

Increase the width of the view and center the image. Adjust the width accordingly (I have set it 50). Try this ...

let usernameTextField: UITextField = {
        let tf = UITextField()


        let imageView = UIImageView()

        let image = UIImage(named: "user-icon")

        imageView.image = image
        imageView.frame = CGRect(x: 0, y: 0, width: 50, height: 15)
        imageView.contentMode = .scaleAspectFit
        tf.leftViewMode = UITextFieldViewMode.always
        tf.leftView = imageView
        tf.addSubview(imageView)


        var placeholder = NSMutableAttributedString(string: "username", attributes: [NSForegroundColorAttributeName: UIColor.lightGray])
        tf.attributedPlaceholder = placeholder
        tf.backgroundColor = UIColor.init(red: 35.0/100.0, green: 34.0/100.0, blue: 34.0/100.0, alpha: 1)
        tf.borderStyle = .roundedRect
        tf.font = UIFont.systemFont(ofSize: 14)
        tf.layer.cornerRadius = 25
        tf.textColor = .white
        tf.layer.borderWidth = 1
        tf.layer.borderColor = UIColor(white: 1, alpha: 0.1).cgColor
        tf.layer.masksToBounds = true
        return tf
    }()

Upvotes: 2

Related Questions