简体   繁体   English

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

[英]Setting up a Custom Cell in a Tableview with SWIFT

I'm trying to create a custom cell that will only be applied to one single CELL in a Section. 我正在尝试创建一个自定义单元格,该单元格将仅应用于Section中的单个CELL。

So a create a custom cass called buttonsTableViewCell, that is pretty much empty and only have one label called weightLabel() code bellow: 因此,创建一个名为buttonsTableViewCell的自定义cass,该cass几乎是空的,只有一个名为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
    }

}

On the Main.storyboard i connected everything: 在Main.storyboard上,我连接了所有东西:

设置自定义类将标签连接到班级设置标识符

Now this is what i'm trying to do in the viewcontroller class, that controls the Tableview that has the cell. 现在,这就是我要在viewcontroller类中尝试做的事情,该类控制具有单元格的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

}

What i'm doing wrong? 我做错了什么? Thanks in advance for the help. 先谢谢您的帮助。

Swift is statically typed language with type inference. Swift是具有类型推断功能的静态类型语言。 So when you first assign the value of cell outside your if condition, the type of the cell variable is set to a normal UITableViewCell . 因此,当您首次在if条件之外分配cell的值时, cell格变量的类型将设置为普通的UITableViewCell
Just use a different variable name like 只需使用其他变量名即可

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM