【发布时间】:2018-11-27 20:01:22
【问题描述】:
在我的故事板中,我对单元格中的子视图(称为缩略图)有一组约束
然后在我的自定义 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()
}
}
我的目标是改变缩略图的高度和宽度,就像你在肖像变量的 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)
}
}
因此,当我旋转手机时,collectionView 变得比高度更宽,里面的单元格也是如此。这有望将单元格设置为重新布局子视图并更改我定义的约束。
【问题讨论】:
-
您将 self(一个 UIColelctionViewCell)作为您的尺寸参考。定义单元格大小的代码在哪里。此单元格的大小是否会根据方向而变化?
-
@Dare 我为 collectionView 添加了我的视图控制器的 sizeForItemAt,它使每个单元格的高度和宽度等于 collectionView 的高度和宽度。当设备旋转到横向模式时,collectionView 变得比高度更宽,并且我的自定义单元格类中的 Portrait 变量被更改为 false。
标签: ios swift uicollectionview nslayoutconstraint iboutlet