使用 SWIFT 在 Tableview 中设置自定义单元格

Setting up a Custom Cell in a Tableview with SWIFT

我正在尝试创建一个自定义单元格,它将仅应用于一个部分中的一个单元格。

因此,创建一个名为 buttonsTableViewCell 的自定义类,它几乎是空的,只有一个名为 weightLabel() 的标签,代码如下:

class buttonsTableViewCell: UITableViewCell {

    @IBOutlet weak var weightLabel: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}

在 Main.storyboard 我连接了一切:

现在这就是我在 viewcontroller class 中尝试做的事情,它控制具有单元格的 Tableview。

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

 var cell = tableView.dequeueReusableCellWithIdentifier("Cell",   forIndexPath: indexPath) as UITableViewCell
          cell.textLabel?.text = "Testing"

if indexPath.row == 1 { // So it only changes this cell
  cell = tableView.dequeueReusableCellWithIdentifier("buttonsCell", forIndexPath: indexPath) as buttonsTableViewCell

  cell.weightLabel?.text = "Weight" // ERROR UITableViewCell does not have a member named 'weightLabel'
}

 return cell

}

我做错了什么?在此先感谢您的帮助。

Swift 是具有类型推断的静态类型语言。因此,当您第一次在 if 条件之外分配 cell 的值时,单元格变量的类型设置为正常的 UITableViewCell
只需使用不同的变量名称,如

if indexPath.row == 1 { 
    var buttonCell = tableView.dequeueReusableCellWithIdentifier("buttonsCell", forIndexPath: indexPath) as buttonsTableViewCell

    buttonCell.weightLabel?.text = "Weight" 
    return buttonCell
}

var cell = tableView.dequeueReusableCellWithIdentifier("Cell",   forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = "Testing"

return cell