在 swift 中初始化时 tableview 的单元格不是 nil

cell of tableview is not nil on initialize in swift

我是 swift 编程的初学者,也是 ios 的新手。我正在尝试制作一个 table 视图,但是 if(cell == nil ) 的条件但是单元格永远不会为 nil 并且不会进入条件这是我的代码。

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    //cell content declaration

        var rightlabel = UILabel(frame: CGRectMake(200, 10, 200, 21))
        var mainTextLabel = UILabel(frame: CGRectMake(10, 10, 200, 21))
        var imageView = UIImageView()
        var cell : UITableViewCell!

        cell = tableView.dequeueReusableCellWithIdentifier("detailsCell") as? UITableViewCell


    //cell content declaration END




if(cell == nil)
{

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

    let test: AnyObject? = myData?.objectForKey("\(indexPath.row + 1)")
    let hrvalue : AnyObject? = test?.objectForKey("name")
    let subtitle : NSNumber? = test?.objectForKey("distance") as? NSNumber
    let icon : String = test?.objectForKey("icon") as String



    //CUSTOM LABEL START FROM HERE

        mainTextLabel.text = hrvalue as? String
        rightlabel.text = "\(subtitle as Float ) k.m. away from here."

        mainTextLabel.font = UIFont.systemFontOfSize(18.0)
        rightlabel.font = UIFont.systemFontOfSize(14.0)

        let image = UIImage(named: icon)
        imageView = UIImageView(image: image!)
        imageView.frame = CGRect(x: 120, y: 10, width: 30, height: 30)

        mainTextLabel.tag = 4
        rightlabel.tag = 50
        imageView.tag = 100

        cell.contentView.addSubview(mainTextLabel)
        cell.contentView.addSubview(rightlabel)
        cell.contentView.addSubview(imageView)



    //CUSTOM LABEL END

}
   if(cell != nil)
   {
println("outside")

    //FATCHING TAG & RETURN CELL

        mainTextLabel = cell.viewWithTag(4) as UILabel
        rightlabel = cell.viewWithTag(50) as UILabel
        imageView = cell.viewWithTag(100) as UIImageView
        }
        return cell

    // FATCHING TAG & RETURN CELL END


    }

cell 永远不能为 nil,因为您已经在 // cell content declaration 区域的开始处启动 cell。所以现在你有一个单元格的实例。因此它不能再往下为零。再往下,您将引入代码检查 if (cell == nil)。因此,代码永远不会被调用。

或者换句话说,您正在尝试冗余地重新实例化单元格。去掉第一个:

cell = tableView.dequeueReusableCellWithIdentifier("detailsCell") as? UITableViewCell

你下面的代码会被调用。

此外,第二个条件(cell != nil)将始终评估为 YES,因为此时您将以某种方式创建一个 cell 实例。所以你可能也想摆脱那个测试。