将图像添加到TextField
问题描述:
即时图标试图将图标添加到我的用户名文本框中,不知何故,我添加了图标,但无法添加任何填充。将图像添加到TextField
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值,它也不会移动任何像素。
答
增加视图的宽度并居中图像。相应地调整宽度(我已将其设置为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
}()
首先我得到了RGB的扩展,所以我不需要使用/ 255。并没有任何方法来提供一个特定的填充?剩下5px,右边10px。因为在另一种情况下,增加宽度可能对此时有用,所以我可能需要更多强大的工作人员。 – Alper
啊好吧..不,没有任何填充..另一种选择是在左侧和右侧的图像中添加透明区域。 – Bilal
Uhm im在不同的问题上挣扎了好几个小时,所以我的大脑现在不工作> _>你能给我一个关于添加透明区域的例子吗 – Alper