如何设置动态单元格高度?
我需要在此方法中设置单元格大小:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
我尝试这样做:
cell.bounds = CGRect(x: cell.bounds.origin.x, y: cell.bounds.origin.y, width: width, height: height)
然后我不能扯下来......
我尝试这种方法:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
但是这个方法首先是ben调用,然后调用这个方法:
cell.bounds = CGRect(x: cell.bounds.origin.x, y: cell.bounds.origin.y, width: width, height: height)
所以..如何改变细胞高度?
答案 0 :(得分:0)
首先,按照正常情况进行设置。 (正常约束[left,right,top,bottom和height]和UICollectionView的IBOutlet。
其次,为高度约束,顶部约束和底部约束制作IBOutlets。
第三,添加 - >
//these are the outlets I am naming generic names but name them what you wish
IBOutlet var collectionViewCellDynamicConstraint: NSLayoutConstraint!
IBOutlet var topConstraintDynamicConstraint: NSLayoutConstraint!
IBOutlet var bottomConstraintDynamicConstraint: NSLayoutConstraint!
//into viewDidLoad
collectionViewCell.addObserver(self, forKeyPath: "contentHeight", options:NSKeyValueObservingOptions.New, context: nil)
topConstraintDynamicConstraint.addObserver(self, forKeyPath: "contentTop", options:NSKeyValueObservingOptions.New, context: nil)
bottomConstraintDynamicConstraint.addObserver(self, forKeyPath: "contentBottom", options:NSKeyValueObservingOptions.New, context: nil)
//create this override func
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//try use this segment below as well but if it doesn't work then remove it and try run again
self.collectionViewCell.sizeThatFits()
//
self.collectionViewCellDynamicConstraint.constant = collectionViewCell.sizeThatFits(CGSizeMake(self.collectionViewCell.frame.size.width, CGFloat.max)).height
// set these values (below) to the space/value that you set them at normally. Often what is needed is a refresh after changing the height of the view/collectionViewCell
self.topSpaceOld.constant = 0.4
self.bottomSpaceOld.constant = 10
}
// you need to de-initialise them before you leave the view or else it will crash
deinit {
self.collectionViewCell.removeObserver(self, forKeyPath: "contentHeight")
self.topConstraintDynamicConstraint.removeObserver(self, forKeyPath: "contentTop"
self.bottomConstraintDynamicConstraint.removeObserver(self, forKeyPath: "contentBottom")
)
}
可能存在一些命名问题,但它应该有效。此代码用于使UITextView在滚动视图内部工作以获得视图的动态高度。它应该是相同的概念。
答案 1 :(得分:-2)
如下所示,您可以使用sizeForItemAtIndexPath委托方法调整单元格大小。您需要为单元格返回CGSize。你能告诉我们你实现这个方法的完整代码吗?
工作示例;
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
return CGSizeMake(width, height);
}