[英]How to set NSLayoutConstraint constant in a collectionView cell?
在我的情節提要中,單元格中的子視圖(稱為“縮略圖”)具有一組約束
然后在我的自定義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變得比它高時更寬時,內部單元也是如此。 希望這會設置單元格以重新布局子視圖並按照我的定義更改約束。
更改常數后,您可能會錯過重新布局
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()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.