【发布时间】:2015-09-08 23:57:36
【问题描述】:
这是使用 AutoLayout、UICollectionView 和 UICollectionViewCell 的应用程序中的一个设计问题,它们根据 AutoLayout 约束及其内容(一些文本)自动调整宽度和高度。
它是一个 UITableView 列表,每个单元格都有自己的宽度和高度,每行根据其内容分别计算。它更像是内置于应用程序(或 WhatsUp)中的 iOS 消息。
很明显,应用应该使用func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize。
问题是在该方法中,应用程序不能调用func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell 或dequeueReusableCellWithReuseIdentifier(identifier: String, forIndexPath indexPath: NSIndexPath!) -> AnyObject 来实例化单元格,用特定内容填充它并计算其宽度和高度。尝试这样做会导致无限期的递归调用或某些其他类型的应用程序崩溃(至少在 iOS 8.3 中)。
解决这种情况的最接近的方法似乎是将单元格的定义复制到视图层次结构中,以让自动布局自动调整“单元格”的大小(就像单元格与父集合视图具有相同的宽度),因此应用程序可以配置单元格具体内容并计算其大小。由于资源重复,这绝对不是修复它的唯一方法。
所有这些都与将 UILabel.preferredMaxLayoutWidth 设置为某个值有关,该值应该是 Auto-Layout 可控(非硬编码),可能取决于屏幕宽度和高度或至少由 Auto-layout 约束定义设置,因此应用程序可以获得计算多行 UILabel 固有大小。
我不想从 XIB 文件中实例化单元格,因为 Storyboard 应该是当今的行业标准,并且我希望减少对代码的干预。
编辑:
下面列出了无法运行的基本代码。因此,只有实例化变量 cellProbe(未使用)会使应用程序崩溃。没有那个调用,应用程序运行顺利。
var onceToken: dispatch_once_t = 0
class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
dispatch_once(&onceToken) {
let cellProbe = collectionView.dequeueReusableCellWithReuseIdentifier("first", forIndexPath: NSIndexPath(forRow: 0, inSection: 0)) as! UICollectionViewCell
}
return CGSize(width: 200,height: 50)
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("first", forIndexPath: NSIndexPath(forRow: 0, inSection: 0)) as! UICollectionViewCell
return cell
}
}
【问题讨论】:
标签: ios uicollectionview autolayout storyboard height