0

I have this function which is used to set size from String length. Something like that - Swift iOS - Tag collection view.

First item in categoriesItems is "Age"

func collectionView(collectionView: UICollectionView,
    layout collectionViewLayout: UICollectionViewLayout,
    sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

        var cellWidth : CGSize = CGSizeFromString(self.categoriesItems[indexPath.row].name);

        return cellWidth
}
4

2 回答 2

1

要确定文本的宽度,请使用以下代码

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-23T20:39:41.070 回答
1

您可以使用NSStringssizeWithAttributes函数来执行此操作。然后你把它作为一个CGSize. 这个大小是文本的大小,所以如果你想在它周围有填充,只需在大小的宽度和高度上添加一个值:

let string: NSString = self.categoriesItems[indexPath.row].name
let size: CGSize = string.sizeWithAttributes(nil) // Enter font/size attributes here
return size
于 2015-03-23T20:46:23.167 回答