如何解决UITextField 的 leftView 上的图像未呈现
我有一个 UITextField
,我想在左侧设置一个图标图像。这是我的代码。谁能指出我的错误?
override func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = self.bounds.height/2
self.layer.borderWidth = 2.0
self.layer.borderColor = UIColor.white.cgColor
self.leftViewMode = .always
let iconImageView = UIImageView(frame: CGRect(x: 5,y: 5,width: self.bounds.height - 10,height: self.bounds.height - 10))
iconImageView.image = UIImage(named: "email")
let iconView = UIView()
iconView.frame = iconImageView.bounds
iconView.addSubview(iconImageView)
self.leftView = iconView
self.tintColor = .white
}
解决方法
这里介绍了如何以编程方式创建自定义字段。
从中你也可以得到将图标设置为 textField 的想法。
class ViewController: UIViewController {
///Creating textField
private let textField: UITextField = {
let tf = UITextField()
tf.leftViewMode = .always
tf.borderStyle = .line
let iconImageView = UIImageView()
iconImageView.image = UIImage(named: "HomeSelected")
iconImageView.contentMode = .scaleAspectFill
let iconView = UIView()
/// Settiing height iconView
iconView.translatesAutoresizingMaskIntoConstraints = false
iconView.heightAnchor.constraint(equalToConstant: 50).isActive = true
iconView.widthAnchor.constraint(equalToConstant: 50).isActive = true
iconView.addSubview(iconImageView)
/// Applying constraints to iconImageView
iconImageView.translatesAutoresizingMaskIntoConstraints = false
iconImageView.topAnchor.constraint(equalTo: iconView.topAnchor,constant: 5).isActive = true
iconImageView.leftAnchor.constraint(equalTo: iconView.leftAnchor,constant: 5).isActive = true
iconImageView.bottomAnchor.constraint(equalTo: iconView.bottomAnchor,constant: -5).isActive = true
///Setting height of iconImageView
iconImageView.heightAnchor.constraint(equalToConstant: 40).isActive = true
iconImageView.widthAnchor.constraint(equalToConstant: 40).isActive = true
tf.leftView = iconView
// Setting Height of Textfield
tf.translatesAutoresizingMaskIntoConstraints = false
tf.heightAnchor.constraint(equalToConstant: 50).isActive = true
return tf
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(textField)
///Apply constraints to text Field.
}
}
结果
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。