我有一个类似Facebook的博客发布View Controller,标题,可选图片和文字。
我正在尝试更新图片的高度限制,以便标题和文字之间没有空格,如下所示:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "blogPostCell", for: indexPath) as? BlogPostCell else{
fatalError("Not an instance of BlogPostCell")
}
cell.headlineLabel.text = blogPosts[indexPath.row].headline
cell.postTextLabel.text = blogPosts[indexPath.row].content
cell.postImage.translatesAutoresizingMaskIntoConstraints = false
let cellHeigtConstraint = cell.postImage.heightAnchor.constraint(equalToConstant: 0)
if let img = blogPosts[indexPath.row].image{
cell.postImage.contentMode = .scaleAspectFit
cellHeigtConstraint.isActive = false
cellHeigtConstraint.constant = self.view.frame.width*0.75
cellHeigtConstraint.isActive = true
cell.postImage.kf.indicatorType = .activity
let url = URL(string: App.rootdir + "/assets/uploads/" + img)
cell.postImage.kf.setImage(with: url)
} else{
cellHeigtConstraint.isActive = false
cellHeigtConstraint.constant = 0
cellHeigtConstraint.isActive = true
}
return cell
}
所以我试图停用约束,然后更改它然后再次激活它。但是,我似乎有两个限制,而不是更新的约束:
2018-01-15 14:20:44.317167+0100 docprice[86466:2062563] [LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x60800009cc00 UIImageView:0x7f80dd53e280.height == 0 (active)>",
"<NSLayoutConstraint:0x60c000289970 UIImageView:0x7f80dd53e280.height == 310.5 (active)>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x60c000289970 UIImageView:0x7f80dd53e280.height == 310.5 (active)>
我想因为出列的单元格,我无法解决这样的约束。但我没有看到另一种方法来实现这一点。
答案 0 :(得分:1)
首先,你应该这样做:
if let img = blogPosts[indexPath.row].image{
cell.postImage.contentMode = .scaleAspectFit
cellHeigtConstraint.constant = self.view.frame.width*0.75
cell.postImage.kf.indicatorType = .activity
let url = URL(string: App.rootdir + "/assets/uploads/" + img)
cell.postImage.kf.setImage(with: url)
} else{
cellHeigtConstraint.constant = 0
}
cell.layoutIfNeeded()
然后我建议每个单元格都有自己的cellHeigtConstraint
,并且它不是所有单元格的单元格。它应该是你BlogPostCell
类中的一个属性。
所以最后你应该有cell.cellHeigtConstraint.constant = 0