gpt4 book ai didi

ios - 将图像添加到 TextField

转载 作者:搜寻专家 更新时间:2023-11-01 07:12:12 26 4
gpt4 key购买 nike

我正在尝试向我的用户名文本字段添加一个图标,我以某种方式添加了该图标,但我无法向其添加任何填充。

我的意思是,我希望它看起来像这样: 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 值,它也不会移动任何像素。

最佳答案

增加 View 的宽度并使图像居中。相应地调整宽度(我将其设置为 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
}()

关于ios - 将图像添加到 TextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44228328/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com