Ivan Cantarino
Ivan Cantarino

Reputation: 3246

iOS - UIButton image doesn't fit as expected

I have a UIButton that has a default image and if a property is set it changes to the property object (an image);

With the default image, everything works properly and the image fits perfectly but when I'm using the image, I don't know why the image doesn't fit.

Here's the code:

    var user: User? {
        didSet {
            self.profileImageButton.setImage(self.user?.profileImage?.withRenderingMode(.alwaysOriginal) ?? #imageLiteral(resourceName: "plus_photo").withRenderingMode(.alwaysOriginal), for: .normal)
        }
    }

    lazy var profileImageButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(#imageLiteral(resourceName: "plus_photo").withRenderingMode(.alwaysOriginal), for: .normal)
        button.layer.cornerRadius = 80/2
        button.contentMode = .scaleAspectFill
        button.layer.masksToBounds = true
        button.clipsToBounds = true
        button.layer.borderWidth = 1
        button.layer.borderColor = .white
        button.addTarget(self, action: #selector(didTapPhoto), for: .touchUpInside)
        return button
    }()

I'm expecting something like this expected

But I'm getting this instead output

Upvotes: 0

Views: 50

Answers (1)

Jože Ws
Jože Ws

Reputation: 1814

Add this line to your button configuration

button.imageView?.contentMode = .scaleAspectFit

Upvotes: 1

Related Questions