2

I have a UICollectionReusableView for a UICollectionView Header Section in code as follows:

    
    var headingLabel: UILabel!
    override init(frame: CGRect) {
       super.init(frame: frame)
       headingLabel = UILabel(frame: CGRectMake(12.0,12.0,frame.width,21.0))
       headingLabel.numberOfLines = 1
       headingLabel.textAlignment = NSTextAlignment.Center
       headingLabel.textColor = UIColor.blackColor()
       self.backgroundColor = UIColor.whiteColor()
       self.addSubview(headingLabel)
    }

I just want the heading to be centered in the display. This is fine so long as I don't rotate the device. If I rotate the device, the label is no longer in the center of the screen.

My guess is this is super simple, I just can't seem to find the answer. My assumption is that I could just programatically add constraints, but I can't quite work out how to do that.

Alternatively, I think there might be some way to force it to redo the headers on a layout change, but I couldn't get that working either.

Any pointers in the right direction would be hugely appreciated.

Section Header Centered

After Rotation to Portrait

Many thanks.

Darren
  • 1,071
  • 1
  • 15
  • 39

2 Answers2

0

You have to invalidate the layout BEFORE the collectionView is re-laid out (which happens in viewDidLayoutSubviews), therefore you must invalidate it in viewWillLayoutSubviews.

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()

    // Handle rotation
    collectionView.collectionViewLayout.invalidateLayout()
}
Frederic Adda
  • 5,905
  • 4
  • 56
  • 71
0
import Foundation
import UIKit
import MaterialComponents

class SectionHeaderAppointment:UICollectionReusableView {

var sectionHeaderlabel: UILabel!
var nameflatButton:MDCButton!

override init(frame: CGRect) {
    super.init(frame: frame)
    configure()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}


override func layoutSubviews() {
    super.layoutSubviews()
    print("Rotation")
     sectionHeaderlabel.frame = CGRect(x: 0, y: 0,  width: frame.width, height: frame.height)
     nameflatButton.frame = CGRect(x: (frame.width - (frame.width/3))/2, y: 6,  width: frame.width/3, height: frame.height - 8)
}
}