UIButton Not Rounding Correctly despite corner radius being half the height

Viewed 745

I am working on a screen that essentially allows a user to input some information for their profile. There is a button on this screen that users can use to select their gender. I want to style these buttons to be rounded, so to accomplish this I make the cornerradius of these buttons to be exactly one half of their height. To get to this screen there are two ways, one is if you are creating your profile, and the second is if you are editing your profile. The issue is, when you are creating the profile the UIButton gets pinched and doesn't round correctly, but when I am editing my profile it rounds correctly, even though it is the exact same code, the only difference is that when you are on the screen to edit your profile, I enable the navigation bar.

The code I use to round the button is here:

        maleButton.layer.borderColor = maleButtonColor.cgColor
        maleButton.setTitleColor(maleButtonColor, for: .normal)
        maleButton.layer.cornerRadius = maleButton.frame.size.height / 2

and this happens in a function that is called in: viewDidLayoutSubviews()

The difference in these buttons are shown below: Note** These are the exact same buttons, only difference is in the second picture the background color has been change to show that the user had selected that button, since they are editing their profile.

enter image description here

enter image description here

I printed out the heights, widths, and cornerradius that the buttons:

When it isn't working here are the values: enter image description here

And when it is working here are the values: enter image description here

As you can see in both cases the corner radius is exactly half the height, so it should be rounding correctly, but it just doesn't. And it is weird because it is the exact same code and same view controller in different situations where it works and doesn't work. This issue has been stumping me, so was hoping someone could help shed some light on it. Thanks!

1 Answers

@Wana_B3_Nerd main reason for this cause is your proportional height. viewDidLoad and viewWillAppear always give height set in storyboard. In viewDidAppear: you will always get updated frame. you can resolve this issues in many ways. I am suggesting ways which i knew.

  1. Do code in viewDidAppear: method

  2. If viewDidAppear: is not applicable and you wish to do code in viewDidLoad then add code in main dispatch queue

     DispatchQueue.main.async {
         // your code
     }
    
  3. Subclass UIButton and add your code in drawRect method.

     class RoundButton: UIButton {
    
         override func draw(_ rect: CGRect) {
              // Your code
          }   
    
     }
    
Related