ios - 如何在 collectionView 单元格中设置 NSLayoutConstraint 常量?
问题描述
在我的故事板中,我在单元格中有一组子视图(称为缩略图)的约束
然后在我的自定义 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 变得比它的高度更宽,里面的单元格也是如此。这有望将单元格设置为重新布局子视图并更改我定义的约束。
解决方案
更改常量后可能会错过重新布局
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()
}
推荐阅读
- analytics - 具有 UDF 维度的多租户数据仓库数据模型
- java - java stream api中中断和继续的类似物?
- reactjs - 将函数导入反应组件并在 onSubmit 中使用
- visual-studio - 如何在 Visual Studio 2019 中更改为 Exec 的 shell?
- ios - youtube-ios-player-helper:嵌入式视频不会增加观看次数
- c++ - 将第一方库与 CMake 链接
- azure - 从 Azure SQL 数据库下载/传输数据到本地的成本是多少?
- gps - 来自 exif 的 GPSTrack
- image - 将 Jupyter 笔记本导出为带有嵌入图像的笔记本
- java - 如果收到错误的对象,如何从 SQS 中删除消息?