文本字段内的图像大小未调整大小

Size of image inside textfield is not resizing

我有一个自定义文本字段,我想将图像放在它的左侧,但是每当我 运行 应用程序时,图像的大小都没有调整,即它的全尺寸而不是提供的宽度和高度。附上代码和图片

ViewController class:(其中存在文本字段) 导入 UIKit

class 注册 2ViewController: UIViewController {

  @IBOutlet weak var Email: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    Email.leftViewMode = .always
    let imageview = UIImageView()
    imageview.frame = CGRect(x: 0, y: 0, width: 5.0, height: 5.0)
    view.addSubview(imageview)
    let icon = UIImage(named: "c.png")
    imageview.image = icon
    Email.leftView = imageview


    // Do any additional setup after loading the view.
}

}

要为您的 imageView 设置框架,您需要子class UITextField 并覆盖 leftViewRect(forBounds:)。下面的代码将导致 20x20 视图从左侧偏移 10 点并垂直居中。

class AwesomeTextField: UITextField {

    override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
        let leftViewHeight: CGFloat = 20
        let y = bounds.size.height / 2 - leftViewHeight / 2
        return .init(x: 10, y: y, width: leftViewHeight, height: leftViewHeight)
    }
}

要将 imageView 添加到 textField,您可以这样做:

class ViewController: UIViewController {

    @IBOutlet weak var textField: AwesomeTextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        let imageView = UIImageView()
        imageView.image = UIImage(named: "c")
        textField.leftView = imageView
        textField.leftViewMode = .always
    }
}

确保在故事板的身份检查器中为 textField 设置适当的 class 名称。