ViewDidLayoutSubviews rotation problems

I am writing an application in iOS 8 / Swift and have a view also UICollectionViewon the screen (screenshot below). Although I use an automaton to make sure they are focused, I also click on viewDidLayoutSubviews()to have the 7 labels that exist inside my view spread throughout the page (and manually do the layout).

To be more specific, what I am doing is to force the columns in my uicollectionview to divide by 7 (split by 7 columns to represent each day of the week in the calendar), and then make labels inside the view divided by 7 so that they matched the columns to show what day of the week it is. I want column headings like a calendar, basically.

This works well for the first time. You can see it here:

Here is my code:

override func viewDidLayoutSubviews()
{
    super.viewDidLayoutSubviews()    
    var labelWidth = (self.view.frame.size.width / 7.0) // view.frame? view.bounds?
    var labelIndex: CGFloat = 0
    var dayHeaders: [UILabel] = [lblSunday, lblMonday, lblTuesday, lblWednesday, lblThursday, lblFriday, lblSaturday]

    //Iterate through each label (day of the week) and change its x position accordingly
    for dayHeader in dayHeaders
    {
        //Loop through each label of the week, and incrementally make it x position further to the right so it spreads out across each column in my uicollection
        (dayHeader as UILabel).frame = CGRectMake(labelWidth * labelIndex, 0, labelWidth, weekHeaderViews.frame.height);

        //Update the index responsible for helping to change a label x position
        labelIndex++
    }

    self.view.setNeedsLayout() //these didn't work btw
    self.view.layoutSubviews() //these didn't help btw
} 

Notice how the columns for each day of the week line up with cells in UICollectionView?

But as soon as I turn the page and then turn it back, it will never look the same. The width of the view is somehow different, but the labels are not spaced the same way. Regardless of how many times I rotate it back and forth, it stays away from it for a long time until I close the application.

What do you think is happening and what can I do to solve this problem? Should I just move everything to automatic layout and add constraints, or is there a simpler solution here?

+4
source share

All Articles