iOS Swift - CGSizeFromString 抛出 CGSizeZero

标签 ios swift view collections cgsize

我有这个函数,用于根据字符串长度设置大小。 类似的东西 - 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
}

最佳答案

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

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

关于iOS Swift - CGSizeFromString 抛出 CGSizeZero,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29219739/

相关文章:

ios - 形状数组 - 协议(protocol)只能用作通用约束

ios - 将支持的界面方向设置为 'All' 只有 MPMoviePlayerController 在 swift 中处于事件状态

ios - 使用 didSet 属性观察器而不声明 'oldValue'

ios - 以关联类型作为属性的协议(protocol)

ios - 如何让 XLPagerTabStrip 将选定的选项卡居中?

ios - 将自定义 UITableViewCell 滚动到键盘上方?

swift - 隐藏搜索栏也隐藏导航栏标题

Android:检测 View 的父 Activity 是否暂停

android - Android中的 "preconcat"矩阵是什么意思?

mysql - 将一次性付款转换为交易