2015-02-23 91 views
7

我一直玩弄動態UICollectionViewCell的,並已注意到在iOS 8上調用cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)UICollectionViewCell返回一個不正確的寬度。目前解決這個問題的唯一解決方法是明確添加寬度約束來強制單元格的寬度。下面的代碼是在細胞亞類中:UICollectionViewCell systemLayoutSizeFittingSize返回不正確的寬度

func calculatePreferredHeightForFrame(frame: CGRect) -> CGFloat { 
    var newFrame = frame 
    self.frame = newFrame 
    let widthConstraint = NSLayoutConstraint(item: contentView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: CGRectGetWidth(frame)) 
    contentView.addConstraint(widthConstraint) 
    self.setNeedsUpdateConstraints() 
    self.updateConstraintsIfNeeded() 
    self.setNeedsLayout() 
    self.layoutIfNeeded() 
    let desiredHeight: CGFloat = self.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height 
    newFrame.size.height = CGFloat(ceilf(Float(desiredHeight))) 
    contentView.removeConstraint(widthConstraint) 
    return CGRectGetHeight(newFrame) 
} 

我知道,與iOS 8和動態UICollectionViewFlowLayout的UICollectionViewCell的內容查看處理的限制不同,但有我丟失的東西嗎?需要做什麼來確保systemLayoutSizeFittingSize在單元格上使用特定的寬度?

我也遇到過這個帖子(Specifying one Dimension of Cells in UICollectionView using Auto Layout),並認爲這可能實際上使我的問題無效。也許UICollectionViewFlowLayout不是爲只有一個動態維度的單元格設計的,但這仍然不能解釋爲什麼單元格會給出不同尋常的寬度。

+0

我有完全相同的問題,我的單元格寬度始終返回爲320(xib視圖大小)。無法真正解決它... – 2015-04-01 14:33:40

+3

你在這個單元格中有多線內的UILabel嗎?如果是這樣,你可能有錯誤的首選最大布局寬度。 – 2015-04-23 14:26:14

+0

@ hris.to如果你再次讀到這個問題,你會發現它與標籤無關,而是整個單元格的大小 – 2015-04-23 14:27:21

回答

5

我遇到過同樣的問題。獲取systemLayoutSize時,關鍵是使用優先級。

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (!self.prototypeCell) { 
     self.prototypeCell = [TrainingMenuCell new]; 
     self.prototypeCell.contentView.translatesAutoresizingMaskIntoConstraints = NO; 
    } 

    [self configureCell:self.prototypeCell forIndexPath:indexPath]; 
    [self.prototypeCell setNeedsLayout]; 
    [self.prototypeCell layoutIfNeeded]; 

    CGFloat width = CGRectGetWidth(collectionView.frame) - 12; 
    CGSize fittingSize = UILayoutFittingCompressedSize; 
    fittingSize.width = width; 

    CGSize size = [self.prototypeCell.contentView systemLayoutSizeFittingSize:fittingSize withHorizontalFittingPriority:UILayoutPriorityRequired verticalFittingPriority:UILayoutPriorityDefaultLow]; 
    return size; 
} 
+0

減法部分不適合我。我從collectionview的寬度中減去20,因爲我的左右部分有10個插入部分。但我仍然以320不是300結尾。 – Nil 2017-09-07 08:04:05

+0

@你有沒有檢查'fittingSize'和'size'變量?我的答案是否優先複製? – 2017-09-07 08:33:33

+0

沒關係。實際上我使用self.prototypeCell而不是self.prototypeCell.contentView。這就是它破裂的原因。 – Nil 2017-09-07 08:34:33