Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Setting corner radius on image nested in UIButton

Tags:

swift

uibutton

I have a button which contains text and an image but I would like the image to have a corner radius on it. When I try to apply the corner radius to the button, it applies to the whole button which I guess is correct. How can I set the corner radius to the image instead?

Here's my code:

let titleButton = UIButton()
titleButton.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
titleButton.setTitle("display name", for: .normal)
titleButton.setImage(#imageLiteral(resourceName: "imgName"), for: .normal)
titleButton.layer.masksToBounds = true
titleButton.layer.cornerRadius = titleButton.frame.width / 2

self.navigationItem.titleView = titleButton
like image 328
Fuad Adetoro Avatar asked Jul 14 '17 11:07

Fuad Adetoro


2 Answers

An UIButton has an UIImageView on it. So to set corner, simply set radius to the layer of the image view

titleButton.imageView?.layer.cornerRadius = 5
like image 62
Fangming Avatar answered Sep 28 '22 03:09

Fangming


if you want rounded then set height and width equal

titleButton.frame = CGRect(x: 0, y: 0, width: 50, height: 50)

titleButton.layer.cornerRadius = titleButton.frame.size.width / 2.0
titleButton.layer.masksToBounds = true

And If you want corner rounded only then

titleButton.frame = CGRect(x: 0, y: 0, width: 50, height: 50)

titleButton.layer.cornerRadius = 10
titleButton.layer.masksToBounds = true
like image 29
BHAVIK Avatar answered Sep 28 '22 03:09

BHAVIK