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
}
To determine the width of text use the following code
where
constraintSize
is some arbitrary size in which you wish to constraint your textYou can use
NSString
ssizeWithAttributes
function to do this. Then you cast it as it as aCGSize
. This size is the size of the text, so if you want there to be padding around it, just add a value to the width and height of the size: