ved*_*ano 12 height storyboard ios autolayout uicollectionview
这是应用程序中的一个设计问题,它使用AutoLayout,UICollectionView和UICollectionViewCell,它可以自动调整宽度和高度,具体取决于AutoLayout约束及其内容(某些文本).
它是一个UITableView列表,每个单元格都有自己的宽度和高度,每个行根据其内容单独计算.它更像是在应用程序(或WhatsUp)中构建的iOS消息.
很明显应用程序应该使用func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize.
问题是在该方法中,app不能调用func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell也不能dequeueReusableCellWithReuseIdentifier(identifier: String, forIndexPath indexPath: NSIndexPath!) -> AnyObject实例化单元格,用特定内容填充它并计算其宽度和高度.尝试这样做会导致无限期的递归调用或其他类型的应用程序崩溃(至少在iOS 8.3中).
解决这种情况的最接近的方法似乎是将单元格的定义复制到视图层次结构中,以允许自动布局自动调整"单元格"(就像单元格具有与父集合视图相同的宽度),因此应用程序可以配置具有特定内容的单元格计算它的大小.由于资源重复,这绝对不应该是修复它的唯一方法.
所有这一切都与将UILabel.preferredMaxLayoutWidth设置为某个值相关联,该值应该是可以依赖于屏幕宽度和高度的自动布局可控(非硬编码)或至少通过自动布局约束定义设置,因此app可以获得多行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
}
}
Run Code Online (Sandbox Code Playgroud)
Ken*_*ham 12
如果使用约束,则无需为每个单元格设置大小.所以你应该删除你的委托方法func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
相反,您需要设置一个大小,方法estimatedItemSize是将其设置为一个值,而不是CGSizeZero告诉布局您还不知道确切的大小.然后布局将询问每个单元格的大小,并在需要时进行计算.
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.estimatedItemSize = someReasonableEstimatedSize()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9741 次 |
| 最近记录: |