swiftuiimageviewstoryboarduiimageibinspectable

UIImage not resizing according to UIImageView size width and height


I am a Swift newbie and I am trying to add an UIImageView on the right of UITextField using Storyboard and @IBInspectable annotation. However, when I define my UIImageView with specific size and add the UIImage, the UIImage is not resizing according to UIImageView size.

Here's my code:

    @IBInspectable var rightImage: UIImage? {
    didSet {
        guard let image = rightImage else {
            return
        }
        rightViewMode = .always
        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        imageView.image = image
        imageView.contentMode = .scaleAspectFit
        rightView = imageView

and here's the result on the screen: Big big icon

If you can tell me what is wrong with my code, do not hesitate. Thanks.


Solution

  • I use constraints based on Matt’s suggestion in the comment, and it's working now:

    let constraints = [
        imageView.heightAnchor.constraint(equalToConstant: 20),
        imageView.widthAnchor.constraint(equalToConstant: 20)
    ]
    
    NSLayoutConstraint.activate(constraints)