我有一个函数,用于根据字符串长度来设置大小。就像那样- 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
}发布于 2015-03-23 20:39:41
若要确定文本的宽度,请使用以下代码
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是您希望约束文本的任意大小。
发布于 2015-03-23 20:46:23
您可以使用NSString的sizeWithAttributes函数来完成这一任务。然后将其转换为CGSize。这个大小是文本的大小,所以如果您想要在它周围填充,只需在大小的宽度和高度上添加一个值:
let string: NSString = self.categoriesItems[indexPath.row].name
let size: CGSize = string.sizeWithAttributes(nil) // Enter font/size attributes here
return sizehttps://stackoverflow.com/questions/29219739
复制相似问题