mkz
mkz

Reputation: 2302

How to set button background image size

I want to create this button in my application. I have added a button to my view in storyboard. Set it's width and height constraints to 60px.

Then in code I've added corner radius and UIImage to background but the image filled the whole button background. The image is 22x22px. I want it to be centered in button like on my screenshot.

var pencilImage = UIImage(named: "pencil")!
pencilBtn.setBackgroundImage(pencilImage, forState: UIControlState.Normal)
pencilBtn.layer.cornerRadius = pencilBtn.frame.size.height / 2
pencilBtn.clipsToBounds = true

What should I code to solve this?

Upvotes: 2

Views: 6916

Answers (1)

Hamza Ansari
Hamza Ansari

Reputation: 3084

Set image using .setImage() method Like this:

pencilBtn.layer.cornerRadius = pencilBtn.frame.size.height / 2
pencilBtn.clipsToBounds = true   
pencilBtn.setImage(UIImage("pencil"), forState: .Normal)
pencilBtn.contentMode = UIViewContentMode.Center

Upvotes: 3

Related Questions