ios - 在 Swift 上创建 UITableView 单元格

标签 ios uitableview swift

我正在尝试在我的委托(delegate)方法 cellForRowAtIndexPath 上使用 swift 创建 UITableViewCell,

代码很简单,就像在 Objective-c 中一样,只是试图将语言变形为 swift。

我在这一行遇到错误

var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell

    if(cell == nil)
    {
        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle,reuseIdentifier:cellIdentifier)
    }

错误是 UITableViewCell 不能转换为“MirrorDisposition”

我查了例子,代码是这样的

if !cell
{let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle,reuseIdentifier:cellIdentifier)
}

但它也会报错。

我做错了什么?

最佳答案

截至最新的测试版(测试版 6)不能将非可选类型与 nil 进行比较

因此,您必须将您的单元格 Var 声明为可选。

像这样的东西会正常工作(在我的脑海中 - 我面前没有 Xcode):

//declare a tableViewCell as an implicitly unwrapped optional...
var cell:UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell

//you CAN check this against nil, if nil then create a cell (don't redeclare like you were doing...
if(cell == nil)
{
  cell = UITableViewCell(style: UITableViewCellStyle.Subtitle,reuseIdentifier:cellIdentifier)
}

关于ios - 在 Swift 上创建 UITableView 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25399193/

相关文章:

ios - 显示Section时如何自定义动画?

ios - 使用 iOS13 使用 NFC 读取 eID 信息时遇到问题

ios - Xcode 8.3 核心数据 "use of undeclared type"错误

uitableview - iOS 8中的自定尺寸(动态高度)单元格-如果没有自定义UITableViewCell,是否可能?

ios - 基于Segment-Control将数组加载到TableView

swift - 从 Firebase 存储中删除文件会导致崩溃

ios - UITextView 在 iPhone 5/5s 上切断文本,但在 iPhone 6 上没有

ios - Swift - 将字符串转换为日期

ios - CATransaction: View 在完成时闪烁

ios - 自动布局约束警告 “Will attempt to recover by breaking constraint”