【问题标题】:Swift: how to use dispatch_once to dequeue a UITableViewCell?Swift:如何使用 dispatch_once 使 UITableViewCell 出队?
【发布时间】:2016-06-30 07:02:15
【问题描述】:

在我的应用程序中,我有一个UITableViewController,其单元格根据其内容(整体图像和文本)非常动态,我需要计算heightForRowAtIndexPath() 中单元格的高度。为了得到这个,我需要按标识符出列一个单元格。我不能简单地实例化其自定义类的单元格,因为它缺少接口生成器中定义的约束,并且演算不正确。相反,我知道在heightForRowAtIndexPath() 中调用dequeueReusableCellWithIdentifier() 会导致无限递归循环。因此,阅读了这里的一些帖子和 Ray Wenderlich 的一些教程,我能够在 heightForRowAtIndexPath() 中编写这段代码

var token: dispatch_once_t = 0
var cell = nil
dispatch_once(&token) {
  cell =  tableView.dequeueReusableCellWithIdentifier("BigTextCell", forIndexPath: indexPath) as! BigTextCell
}
/*adjust cell constraints and return its height*/

这似乎对每个人都有效(至少在 Objective-C 中),但我不知道为什么它不适合我。正如预期的那样,它在无限循环中阻塞。为什么? 我必须承认我从未使用过单例,而且我对他们不熟悉,但我认为这是正确的。 有什么想法吗?

更新

我刚刚尝试了以下方法,但它不起作用:

  var cell:BigTextCell!
  dispatch_once(&onceToken) {
    cell =  tableView.dequeueReusableCellWithIdentifier("BigTextCell", forIndexPath: indexPath) as! BigTextCell
  }
  for constraint in cell.paragraph.constraints {
    if (constraint.identifier == "longTextConstraint") {
      constraint.constant = cell.paragraph.sizeThatFits(CGSize(width: cell.paragraph.frame.width, height: CGFloat.max)).height
      return constraint.constant
    }
  }

【问题讨论】:

    标签: ios objective-c swift uitableview singleton


    【解决方案1】:

    在方法外声明var onceToken = dispatch_once_t()

    把它作为你的 ViewController 的一个属性

    class ViewController: UITableViewController {
    
        var onceToken = dispatch_once_t()
    
        func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath:  NSIndexPath) -> CGFloat {
            dispatch_once(&onceToken) {
                //your code
            }
        }
    }
    

    【讨论】:

    • 感谢您的回答,但恐怕它不起作用。我刚刚更新了我的问题,我根据你的建议编写了代码,onceToken 作为类的属性......也许我错过了一些东西
    • 也许您应该声明一个全局单元格。因为您需要 heightForRowAtIndexPath() 中的相同源单元格。全局单元可以工作
    • 抱歉,全局单元格是什么意思?也许我应该在一开始就在 viewDidLoad 中将它出列?
    • 这正是我尝试酵母日的方法,为 dequeue 函数提供了第 0 部分(唯一部分)和第 1 行的索引路径的新实例,但我得到了错误索引路径的异常......也许它不会那样工作......
    • 界面生成器在 viewDidLoad 期间得到错误的大小。在 viewWillAppear 中它是正确的。也许尝试在 viewWillAppear 中初始化
    猜你喜欢
    • 2014-07-24
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多