【发布时间】:2014-10-27 20:18:42
【问题描述】:
我已经阅读了很多关于向 UICollectionView 添加标题的帖子。在 Swift 的 iOS 7+ 应用程序中,我正在尝试添加一个带有 UILabel 的标题,其高度应根据 UILabel 的高度进行调整。 UILabel 的行数 = 0。
我已经在 IB 中使用 AutoLayout 设置了标题
ViewController 实现了UICollectionViewDelegate, UICollectionViewDataSource。我没有为标题设置自定义类,但正在使用这两个函数:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
//description is a String variable defined in the class
let size:CGSize = (description as NSString).boundingRectWithSize(CGSizeMake(CGRectGetWidth(collectionView.bounds) - 20.0, 180.0), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont(name: "Helvetica Neue", size: 16.0)], context: nil).size
return CGSizeMake(CGRectGetWidth(collectionView.bounds), ceil(size.height))
}
func collectionView(collectionView: UICollectionView!, viewForSupplementaryElementOfKind kind: String!, atIndexPath indexPath: NSIndexPath!) -> UICollectionReusableView! {
var reusableview:UICollectionReusableView = UICollectionReusableView()
if (kind == UICollectionElementKindSectionHeader) {
//listCollectionView is an @IBOutlet UICollectionView defined at class level, using collectionView crashes
reusableview = listCollectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "ListHeader", forIndexPath: indexPath) as UICollectionReusableView
let label = reusableview.viewWithTag(200) as UILabel //the UILabel within the header is tagged with 200
label.text = description //description is a String variable defined in the class
}
}
return reusableview
}
文本的显示似乎正常,但高度计算似乎不起作用(见下面的屏幕截图)。另外,我认为我也不能通过 collectionView...referenceSizeForHeaderInSection 函数访问 UILabel。有关如何正确计算 CGSize 的任何建议?
【问题讨论】:
-
我无法真正解决问题。但我确实找到了涉及 UX 工作流程更改的解决方法。我为标题定义了一个固定的标题高度和固定的大小。如果标题较长,我会截断文本,但允许用户单击它进入显示全文的模式视图。在 iOS 中,我总是发现很难为简单的问题实施解决方案。
-
@Dean 我想我必须做同样的事情,可能是在 UI 中的某处放置一个“阅读更多...”按钮......
标签: ios ios7 swift uicollectionview