iOS Swift - CGSizeFromString throws CGSizeZero

两盒软妹~` 提交于 2019-12-12 04:55:58

问题


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
}

回答1:


To determine the width of text use the following code

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

where constraintSize is some arbitrary size in which you wish to constraint your text




回答2:


You can use NSStrings sizeWithAttributes function to do this. Then you cast it as it as a CGSize. 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:

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


来源:https://stackoverflow.com/questions/29219739/ios-swift-cgsizefromstring-throws-cgsizezero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!