将图像添加到TextField

时间:2017-05-28 14:22:11

标签: ios swift uitextfield

我试图在我的用户名文本字段中添加一个图标,不知何故我添加了图标,但我无法添加任何填充。

我的意思是,我希望它看起来像这样: enter image description here

我得到的是这个: 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
    }()

这是我的代码块。即使我更改了x和y值,它也不会移动任何像素。

1 个答案:

答案 0 :(得分:2)

增加视图宽度并使图像居中。相应地调整宽度(我已将其设置为50)。试试这个......

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
    }()