如何在Swift中使用dequeueReusableCellWithIdentifier? [英] How to use dequeueReusableCellWithIdentifier in Swift?

查看:139
本文介绍了如何在Swift中使用dequeueReusableCellWithIdentifier?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我取消注释

tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?)

我收到错误

let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)

表示的UITableView?没有名为'dequeueReusableCellWithIdentifier'的成员

如果我打开tableview然后错误消失了,但在Objective-C中我们通常会检查单元格是否存在,如果不存在,我们创建一个新单元格。在Swift中,由于提供的样板文件使用 let 关键字并解开一个可选项,如果它是零,我们就无法重新分配它。

If I unwrap the tableview then the error goes away, but in Objective-C we would normally check whether or not the cell exists, and if it does not we create a new one. In Swift, since the boilerplate provided uses the let keyword and unwraps an optional, we can't reassign it if it's nil.

在Swift中使用dequeueReusableCellWithIdentifier的正确方法是什么?

What's the proper way to use dequeueReusableCellWithIdentifier in Swift?

推荐答案

您可以隐式地将参数解包到方法中转换 dequeueReusableCellWithIdentifier 的结果,以提供以下简洁代码:

You can implicitly unwrap the parameters to the method and also cast the result of dequeueReusableCellWithIdentifier to give the following succinct code:

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell

    //configure your cell

    return cell
}

这篇关于如何在Swift中使用dequeueReusableCellWithIdentifier?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆