Search code examples
iosswiftxcodeswift3xcode8

How to resize an image inside an UIButton programmatically?


I have this UIButton and an image to fit in. I don't want that the image take all the space inside the button but just a little part of it right in the center, but if I resize the button it will resize the image too. How can I do that, is there an option to set whatever dimension I want independently from the size of the UIButton? Thanks!


Solution

  • This can be done through code in the following way:

        let imageSize:CGSize = CGSize(width: 20, height: 20)
    
        let button:UIButton = UIButton(type: UIButton.ButtonType.custom)
        button.frame = CGRect(x: 200, y: 200, width: 60, height: 60)
        button.backgroundColor = UIColor.yellow
        button.setImage(UIImage(named: "chat.png"), for: UIControl.State.normal)
    
        // The below line will give you what you want
        button.imageEdgeInsets = UIEdgeInsets(
            top: (button.frame.size.height - imageSize.height) / 2,
            left: (button.frame.size.width - imageSize.width) / 2,
            bottom: (button.frame.size.height - imageSize.height) / 2,
            right: (button.frame.size.width - imageSize.width) / 2)
    
        self.view.addSubview(button)
    

    This way, you can achieve what you wanted.