How to make UIButton circle?

I am trying to make UIButton in cells a perfect circle. Unfortunately, the circle is formed based on the background image, not the UIButton frame.

Code for creating a circle:

cell.StoryViewButton.setImage(image, forState: .Normal)
cell.StoryViewButton.frame = CGRectMake(50, 8, 100, 100)
cell.StoryViewButton.layer.masksToBounds = false
cell.StoryViewButton.layer.cornerRadius = cell.StoryViewButton.frame.width/2
cell.StoryViewButton.clipsToBounds = true

The result is as follows: Output Images for each cell

What can I do to get the perfect circle button frames I want?

+4
source share
3 answers

Try something like this

 cell.StoryViewButton.layer.masksToBounds = true
 cell.StoryViewButton.layer.cornerRadius = cell.StoryViewButton.frame.width/2

If you need to create a view circle, you must set masksToBounds to true, do not set clipToBounds

Hope this helps you.

+8
source

Swift 4

You can apply the following function to any view, including buttons.

func makeViewCircular(view: UIView) {
    view.layer.cornerRadius = view.bounds.size.width / 2.0
    view.clipsToBounds = true
}

Great.

, viewDidLoad. - , , , , , , . , override func viewDidLayoutSubviews().

, , , -.

+1

. . , . , , , "CGRectMake (50, 8, 120, 120)", , , .

 cell.StoryViewButton.setImage(image, forState: .Normal)
 cell.StoryViewButton.frame = CGRectMake(50, 8, 120, 120)
 cell.StoryViewButton.layer.cornerRadius = self.btn.frame.width/2;
 cell.StoryViewButton.layer.masksToBounds = true

, .

0

All Articles