ios - UICollectionReusableView 标题不调整旋转大小 - 约束?

标签 ios swift uicollectionview nslayoutconstraint uicollectionreusableview

我有一个 UICollectionReusableView 用于 UICollectionView 标题部分,代码如下:

    
    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)
    }

我只希望标题在显示中居中。只要我不旋转设备,就可以了。如果我旋转设备,标签将不再位于屏幕中央。

我的猜测是这非常简单,我似乎找不到答案。我的假设是我可以通过编程方式添加约束,但我不太清楚该怎么做。

或者,我认为可能有一些方法可以强制它在布局更改时重做标题,但我也无法让它工作。

任何指向正确方向的指示都将不胜感激。

Section Header Centered

After Rotation to Portrait

非常感谢。

最佳答案

您必须在 collectionView 重新布局之前使布局无效(这发生在 viewDidLayoutSubviews 中),因此您必须在 viewWillLayoutSubviews 中使它无效。

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()

    // Handle rotation
    collectionView.collectionViewLayout.invalidateLayout()
}

关于ios - UICollectionReusableView 标题不调整旋转大小 - 约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31387109/

相关文章:

ios - typedef 行 : 上的“预期标识符”错误

ios - 解析 : One app on parse. com 将被多个 iOS 应用程序访问。它有效吗?

swift - 在 Swift 中缓存图像?

ios - 在 UIAlertController Action 中关闭 UIViewController 会导致崩溃

ios - Swift 4 UICollectionView 检测滚动结束

ios - 点击时突出显示 uicollectionview 单元格

ios - 以 UILabel 文本的第一行居中图像

ios - 如何在键盘上方添加按钮

ios - 为什么为 UINavigationItem 设置自定义 backBarButtonItem 会导致出现双后退按钮?

ios - Swift中如何根据图片的高度设置UITableViewCell的大小