如何在 collectionView 单元格中设置 NSLayoutConstraint 常量?

How to set NSLayoutConstraint constant in a collectionView cell?

在我的故事板中,我对单元格中的子视图(称为缩略图)设置了一组约束

然后在我的自定义 collectionView 单元格中:

class PostViewCell: UICollectionViewCell {

var portrait: Bool? {
    didSet {
        if portrait == true {
            print(self.bounds.height)
            thumbnailWidthConstraint.constant = self.bounds.width
            thumbnailHeightConstraint.constant = self.bounds.height/2
            thumbnailHeightConstraint.isActive = true
        } else {
            thumbnailWidthConstraint.constant = self.bounds.width/2
            thumbnailHeightConstraint.constant = self.bounds.height
        }
        self.layoutIfNeeded()
    }
}
@IBOutlet weak var thumbnailCenterYConstraint: NSLayoutConstraint!
@IBOutlet weak var thumbnailWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var thumbnailHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var thumbnailCenterXConstraint: NSLayoutConstraint!

override func layoutSubviews() {
    if self.bounds.width > self.bounds.height {
        portrait = false
    } else {
        portrait = true
    }
    super.layoutSubviews()
}

}

我的目标是像您在 portrait 变量的 didSet 方法中看到的那样更改缩略图的高度和宽度。然而,到目前为止,这似乎并不成功。它打印 536 的 self.bounds.height 并且在应用程序中它似乎是这个高度,而不是我试图在约束中设置的高度的一半。我错过了什么步骤?为什么这不起作用?谢谢!

编辑:在我的包含 collectionView 单元格的视图控制器中:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    postsCollectionView.collectionViewLayout.invalidateLayout()
    postsCollectionView.layoutIfNeeded()
    super.viewWillTransition(to: size, with: coordinator)
}

此集合视图在我的视图控制器中称为 "postsCollectionView"。另外,我有这个:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    if collectionView == timelineCollectionView {
        return CGSize(width: CGFloat(2.5), height: collectionView.bounds.height)
    } else {
        return CGSize(width: collectionView.bounds.size.width, height: collectionView.bounds.size.height)
    }
}

因此,当我旋转 phone 并且 collectionView 变得比高度宽时,内部的单元格也是如此。这有望将单元格设置为重新布局子视图并更改我定义的约束。

更改常量后可能会错过重新布局

var portrait: Bool? {
    didSet {
        if portrait == true {
            print(self.bounds.height)
            thumbnailWidthConstraint.constant = self.bounds.width
            thumbnailHeightConstraint.constant = self.bounds.height/2
            thumbnailHeightConstraint.isActive = true
        } else {
            thumbnailWidthConstraint.constant = self.bounds.width/2
            thumbnailHeightConstraint.constant = self.bounds.height
        }

        self.layoutIfNeeded() // or  self.contentView.layoutIfNeeded() 
    }
}

您还需要响应系统方向变化

func viewWillTransition(to size: CGSize, 
               with coordinator: UIViewControllerTransitionCoordinator) {
  collectionView.collectionViewLayout.invalidateLayout()
  collectionView.layoutIfNeeded()
}