Search code examples
iosswiftcornerradiusviewdidlayoutsubviews

Auto resizing corner radius using viewDidLayoutSubviews() not updating the view before it is displayed


I'm new to swift and Xcode so there may be a simple answer or better way to do this. I am trying to make rounded edges to my buttons in all size iOS devices and the best way that I have found so far is using this method:

    override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    for i in 0..<buttons.count {
        self.buttons[i].layer.cornerRadius = self.buttons[i].bounds.size.height / 2
    }
    examResultsBackButtonOutlet.layer.cornerRadius = examResultsBackButtonOutlet.bounds.size.height / 2
}

// Build UI

func loadUI() {

    // Round the edges, change color background, font

    titleOutlet.mainMenuStyle("", 75, earthGreenWithAlpha)
    for i in 0..<buttons.count {
        buttons[i].mainMenuStyle("", 40)
    }

    print("Main Menu successful load")

}

I call the loadUI() method in my viewDidLoad method for what its worth:

    //MARK: viewDidLoad()

override func viewDidLoad() {

    super.viewDidLoad()

    // Load the UI
    loadUI()
    loadExamResultsView()
    mainMenu()
    examResultsStackView.isHidden = true
    loadStoredScores()
    loadStoredSettings()

}

The issue presents itself not when I start the app for the first time (this is the first scene/View Controller), rather the issue occurs when I segue back to this scene from my second View Controller.

What happens is the buttons are formatted weird for about a half a second, then they are reformatted perfectly:

Correctly formatted screenshot

Incorrectly formatted screenshot

You'll notice the second image (which only occurs for about 0.5 seconds) has much more intense corner radius'.

How can I prevent this from happening so that the user only sees the perfectly round corner radius' for each button and not the poor janky ones?

Thanks!


Solution

  • Thanks for everyone's feedback but here is what fixed it for me:

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        for i in 0..<buttons.count {
            self.buttons[i].layer.cornerRadius = self.buttons[i].bounds.size.height / 2
        }
        examResultsBackButtonOutlet.layer.cornerRadius = examResultsBackButtonOutlet.bounds.size.height / 2
    }
    

    This replaced the original post:

    override func viewDidLayoutSubviews() {
         super.viewDidLayoutSubviews()
         for i in 0..<buttons.count {
         self.buttons[i].layer.cornerRadius = self.buttons[i].bounds.size.height / 2
      }
      examResultsBackButtonOutlet.layer.cornerRadius = examResultsBackButtonOutlet.bounds.size.height / 2 }
    

    Thanks!