【问题标题】:No 'dequeueReusableCellWithIdentifier' candidates produce the expected contextual result type 'DynamicTableViewCell?'没有“dequeueReusableCellWithIdentifier”候选产生预期的上下文结果类型“DynamicTableViewCell?”
【发布时间】:2016-08-10 19:25:09
【问题描述】:

实现自定义表格视图单元格并在 dequeueReusableCellWithIdentifier 上收到以下错误,任何人都可以帮忙。

代码:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

        //static DynamicTableViewCell *cell = nil;
        var cell : DynamicTableViewCell?

        var token: dispatch_once_t = 0
        dispatch_once(&token) { () -> Void in
            cell = tableView.dequeueReusableCellWithIdentifier("cell")
        }

        self.setUpCell(cell!, indexPath: indexPath)

        return self.calculateHeightForConfiguredSizingCell(cell!)

    }

【问题讨论】:

  • static DynamicTableViewCell 用词自相矛盾。这段代码根本无法工作。 dequeueReusableCellWithIdentifier 外面的cellForRowAtIndexPath 毫无意义。
  • 我已经评论了那条线,但我没有使用它,我有一个相同的客观 c 版本,可以参考:-github.com/tjosten/iOS-UITableViewCell-with-dynamic-height我正在尝试用 swift 编写它
  • 可能你应该只在tableView的方法cellForRowAtIndexPath中使用dequeueReusableCellWithIdentifier。对于自定义单元格,您应该在加载控制器时注册您的自定义类(例如在 viewDidLoad 中)

标签: swift


【解决方案1】:

我不确定你的做法是否足够稳定,但你指出的 Objective-C 代码可以翻译成 Swift 为:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    struct My {
        static var cell : DynamicTableViewCell?
        static var token: dispatch_once_t = 0
    }

    dispatch_once(&My.token) { () -> Void in
        My.cell = tableView.dequeueReusableCellWithIdentifier("cell") as? DynamicTableViewCell
    }

    self.setUpCell(My.cell!, indexPath: indexPath)

    return self.calculateHeightForConfiguredSizingCell(My.cell!)
}

错误消息 No 'dequeueReusableCellWithIdentifier' Candidates generate the expected contextual result type 'DynamicTableViewCell?' 是说 dequeueReusableCellWithIdentifier 的返回类型是 UITableViewCell? 不能分配给变量输入DynamicTableViewCell?。您只需要显式强制转换来抑制此错误。

但除此之外,您需要将本地 celltoken 设为静态。

您还应该知道,Swift 3 已将 dispatch_once 从其标准库中排除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多