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

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

问题描述

我想要一个UITableView,其中包含使用dequeueReusableCellWithIdentifiersubtitle样式的单元格.

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.

我已经进行了更多研究,并查看了此视频教程,但他创建了我认为在我以前在Obj-C中实现相同效果时,我认为没有必要单独使用UITableViewCell中的subclass.

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天全站免登陆