gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 14:01:30 25 4
gpt4 key购买 nike

在我的 Storyboard中,我对单元格中的 subview (称为缩略图)设置了一组约束

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 单元格的 View Controller 中:

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

此 Collection View 在我的 View Controller 中称为“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 变得比高度宽,里面的单元格也是如此。这有望将单元格设置为重新布局 subview 并更改我定义的约束。

最佳答案

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

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

关于ios - 如何在 collectionView 单元格中设置 NSLayoutConstraint 常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53507253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com