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

时间:2018-11-27 20:01:23

标签: ios swift uicollectionview nslayoutconstraint iboutlet

在情节提要中,单元格中的子视图(称为“缩略图”)具有一组约束条件

enter image description here

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

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方法中看到的那样。但是,到目前为止,这似乎没有成功。它输出的self.bounds.height为536,在应用程序中似乎是这个高度,而不是我尝试在约束中设置的高度的一半。我想走哪一步?为什么这不起作用?谢谢!

编辑:在包含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)
    }
}

因此,当我旋转手机时,collectionView变得比高度还宽,内部的单元也是如此。希望这会设置单元格以重新布局子视图并按照我的定义更改约束。

1 个答案:

答案 0 :(得分:1)

更改常数后,您可能会错过重新布局

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