如何在 Swift 中设置 UITableViewCellStyleSubtitle 和 dequeueReusableCell? [英] How to Set UITableViewCellStyleSubtitle and dequeueReusableCell in Swift?

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

问题描述

我想要一个带有 subtitle 样式的单元格的 UITableView,使用 dequeueReusableCellWithIdentifier.

I'd like a UITableView with subtitle-style cells that use dequeueReusableCellWithIdentifier.

我原来的 Objective-C 代码是:

My original Objective-C code was:

static NSString *reuseIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
if(!cell)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
}

在 SO 上搜索了几个 UITableView 问题之后,我想像这样用 Swift 编写它:

After searching the few UITableView questions here already on SO, I thought to write it in Swift like so:

tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "Cell")

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

但这并不能让我说我想要 subtitle 样式.所以我尝试了这个:

But that doesn't let me say I want a subtitle style. So I tried this:

var cell :UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")

它给了我一个 subtitle 单元格,但它不允许我 dequeueReusableCellWithIdentifier.

Which gives me a subtitle cell, but it doesn't let me dequeueReusableCellWithIdentifier.

我进行了更多研究并查看了此视频教程,但他创建一个单独的 UITableViewCellsubclass,我认为这是不必要的,因为我之前在 Obj-C 中实现了同样的效果.

I've researched some more and looked at this video tutorial, but he creates a separate subclass of UITableViewCell which I assume is unnecessary as I accomplished this same effect previously in Obj-C.

有什么想法吗?谢谢.

推荐答案

记住 UITableView 在函数中被定义为可选的,这意味着你的初始单元格声明需要检查可选的在物业.此外,返回的排队单元也是可选的,因此请确保对 UITableViewCell 进行可选转换.之后,我们可以强制展开,因为我们知道我们有一个单元格.

Keep in mind that UITableView is defined as an optional in the function, which means your initial cell declaration needs to check for the optional in the property. Also, the returned queued cell is also optional, so ensure you make an optional cast to UITableViewCell. Afterwards, we can force unwrap because we know we have a cell.

var cell:UITableViewCell? = 
tableView?.dequeueReusableCellWithIdentifier(reuseIdentifier) as? UITableViewCell
if (cell == nil)
{
   cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, 
                reuseIdentifier: reuseIdentifier)
}
// At this point, we definitely have a cell -- either dequeued or newly created,
// so let's force unwrap the optional into a UITableViewCell
cell!.detailTextLabel.text = "some text"

return cell

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

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