ios - 动态调整集合视图单元格的大小
问题描述
我有这个更新的旧代码示例,但我仍然是新手,不知道如何解决这个错误:
在包含集合视图的类中:
var array = ["Just testing this out"]
现在在 UICollectionViewDelegateFlowLayout 扩展中:
private func estimateFrameForText(text: String) -> CGRect {
//we make the height arbitrarily large so we don't undershoot height in calculation
let height: CGFloat = 1000
let size = CGSize(width: 398, height: height)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.light)]
return NSString(string: text).boundingRect(with: size, options: options, attributes: attributes, context: nil)
}
还:
private func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
var height: CGFloat = 295
//we are just measuring height so we add a padding constant to give the label some room to breathe!
var padding: CGFloat = 14
//estimate each cell's height
if let text = array[indexPath.item].text {
height = estimateFrameForText(text).height + padding
}
return CGSize(width: 398, height: height) }
这是我得到错误的地方:
if let text = array[indexPath.item].text
这是来自集合视图单元类的 UILabel 我不知道在哪里实现:
@IBOutlet weak var TextPosted: UILabel!
解决方案
您的测试阵列需要一些调整。尝试将其声明为可选(因为它可能会与从某处加载的实际数据一起使用)。
var array: [String]? = ["Just testing this out", "Another test"]
然后这个:
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return array?.count ?? 0
}
然后在 collecitonView sizeForItemAtIndexPath 函数中更新 if let 语句:
if let text = array?[indexPath.item]{
}
顺便说一句,几天前我写了一个开源扩展来测量字符串大小。
希望这可以帮助。
推荐阅读
- javascript - visnetwork 节点标题中的闪亮动作按钮
- c# - ASP.NET MVC 应用程序中的 IIS 服务器 MIME 错误
- reactjs - 如何使用组件方法测试状态变化
- c# - 如何配置 quickfix/n 故障转移
- javascript - 不知何故,我的数据的每一秒元素都会被删除(我需要删除循环中的每个元素)
- linux - 如何触发 Git-webhook 以通过 Jenkinsfile 将任何受保护的 github 分支合并到测试分支?
- sql - Crystal Reports 错误 - 不正确的语法错误
- javascript - 将对象拆分为特定的 id 字符串
- reactjs - React Hooks - 在不违反 Hooks 规则的情况下返回 useContext
- rxjs - 在订阅(rxjs)中初始化变量总是未定义的Angular 6