erdwfddsfd fsdfsdffd
erdwfddsfd fsdfsdffd

Reputation: 55

Swift circular button

I want to create a button that has the shape of a circle with an image inside of it. The button itself is added on the Storyboard interface.

Here is my code:

imageButton.frame = CGRect(x: 160, y: 160, width: 160, height: 160)
imageButton.layer.cornerRadius = 0.5 * imageButton.bounds.size.width
imageButton.layer.borderColor = UIColor.lightGray.cgColor
imageButton.layer.borderWidth = 1.0
imageButton.clipsToBounds = true
imageButton.setBackgroundImage(userImg, for: .normal)

However, the button has the shape of a rectangle and the picture is not being displayed properly, i.e. it is stretched the wrong way.

Any suggestions on how to fix this will be appreciated.

Output

Upvotes: 1

Views: 4543

Answers (1)

Krunal
Krunal

Reputation: 79726

Your code seems working fine, there is not issue with your code, you've shared in your question.

Here I tried that:

let imageButton = UIButton()
imageButton.frame = CGRect(x: 160, y: 160, width: 160, height: 160)
imageButton.layer.cornerRadius = 0.5 * imageButton.bounds.size.width
imageButton.layer.borderColor = UIColor.lightGray.cgColor
imageButton.layer.borderWidth = 1.0
imageButton.clipsToBounds = true
imageButton.setBackgroundImage(#imageLiteral(resourceName: "2"), for: .normal)

//imageButton.setImage(#imageLiteral(resourceName: "2"), for: .normal)

self.view.addSubview(imageButton)

Result:

enter image description here

Try to check, other functionality of your code, affecting your button.

Upvotes: 4

Related Questions