iOS Swift – CGSizeFromString抛出CGSizeZero

我有这个function是用来从string长度设置大小。 类似的东西 – Swift iOS – 标签集合视图 。

项目中的第一项是“年龄”

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是您希望限制文本的任意大小

你可以使用NSStringsizeWithAttributes函数来做到这一点。 然后你把它作为一个CGSize 。 这个大小是文本的大小,所以如果你想要在其周围填充,只需要在大小的宽度和高度上添加一个值:

 let string: NSString = self.categoriesItems[indexPath.row].name let size: CGSize = string.sizeWithAttributes(nil) // Enter font/size attributes here return size