我有这个函数,用于根据字符串长度设置大小。 类似的东西 - Swift iOS - Tag collection view .
categoriesItems 中的第一项是“年龄”
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var cellWidth : CGSize = CGSizeFromString(self.categoriesItems[indexPath.row].name);
return cellWidth
}
最佳答案
要确定文本的宽度,请使用以下代码
let text = self.categoriesItems[indexPath.row].name
let rect = text.boundingRectWithSize(constraintSize, options: NSStringDrawingOptions.UsesFontLeading, attributes: [NSFontAttributeName : UIFont.systemFontOfSize(17)], context: nil)
return rect.size.width
其中 constraintSize
是您希望限制文本的任意大小
关于iOS Swift - CGSizeFromString 抛出 CGSizeZero,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29219739/