【问题标题】:Image on UITextField's leftView is not being renderedUITextField 的 leftView 上的图像未呈现
【发布时间】:2021-02-07 18:05:30
【问题描述】:

我有一个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
}

【问题讨论】:

    标签: swift uitextfield layoutsubviews


    【解决方案1】:

    您可以通过以下方式以编程方式创建自定义字段。
    从这里你也可以得到将 icon 设置为 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.
        }
    
    
    }
    
    

    结果

    【讨论】: