在UICollectionview子类的Viewdidiload函数中增加这句代码
(collectionView.collectionViewLayout as! UICollectionViewFlowLayout).estimatedItemSize = CGSize(width: 20, height: 20)
在UICollectionviewCell子类中增加这一段代码
override func preferredLayoutAttributesFittingAttributes(layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes! {
let attributes = super.preferredLayoutAttributesFittingAttributes(layoutAttributes)
attributes.frame = NSString(string: styleLabel.text!).boundingRectWithSize(CGSize(width: intmax_t(), height: Int(styleLabel.frame.size.height)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName:styleLabel.font], context: nil)
return attributes
}