首页 > 解决方案 > 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
}

标签: swiftuitextfieldlayoutsubviews

解决方案


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


}

结果

文本字段结果


推荐阅读