为什么数据不填充在我的自定义UI表格视图单元格中

我从服务器获取数据,我想把它放在我自定义的UITableViewCell中

这是故事板中的单元格

在这里输入图像说明

如你所见,有两件事情:

  1. 喜好标签
  2. 三个button

当我从服务器接收数据时,我这样做:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("OneResponseTableViewCell") as! OneResponseTableViewCell let oneResponse = self.responses[indexPath.row] cell.preferencesLabel?.text = oneResponse.restaurantName print("row = \(indexPath.row), timesOptions = \(oneResponse.timeOptions)") if oneResponse.timeOptions.count >= 1{ cell.firstTimeOption!.titleLabel?.text = oneResponse.timeOptions[0]; } if oneResponse.timeOptions.count >= 2 { cell.secondTimeOption!.titleLabel?.text = oneResponse.timeOptions[1]; } if oneResponse.timeOptions.count >= 3 { cell.thirdTimeOption!.titleLabel?.text = oneResponse.timeOptions[2]; } return cell } 

如你所见,我正在查阅标签和button,

但是,button不被改变,请看结果:

在这里输入图像说明

我试图把代码中看到的打印 ,并打印的数据是正确的,请看

 row = 0, timesOptions = ["7:30 pm", "8:30 pm", "9:00 pm"] row = 1, timesOptions = ["11:30 am", "12:00 pm", "12:30 pm"] row = 2, timesOptions = ["7:30 pm", "8:30 pm", "9:00 pm"] row = 3, timesOptions = ["7:30 pm", "8:30 pm", "9:00 pm"] 

为什么在单元格中不正确?

对不起,我的英语不好

设置button标题时,应该使用setTitle(forState:) 。 例如:

 if oneResponse.timeOptions.count >= 1 { cell.firstTimeOption.setTitle(oneResponse.timeOptions[0], forState: .Normal) } if oneResponse.timeOptions.count >= 2 { cell.secondTimeOption.setTitle(oneResponse.timeOptions[1], forState: .Normal) } if oneResponse.timeOptions.count >= 3 { cell.thirdTimeOption.setTitle(oneResponse.timeOptions[2], forState: .Normal) } 

顺便说一句,因为你正在重用单元格,所以你应该检查这些if语句的else子句,如果失败则隐藏该button:

 if oneResponse.timeOptions.count >= 1 { cell.firstTimeOption.setTitle(oneResponse.timeOptions[0], forState: .Normal) cell.firstTimeOption.hidden = false } else { cell.firstTimeOption.hidden = true } if oneResponse.timeOptions.count >= 2 { cell.secondTimeOption.setTitle(oneResponse.timeOptions[1], forState: .Normal) cell.secondTimeOption.hidden = false } else { cell.secondTimeOption.hidden = true } if oneResponse.timeOptions.count >= 3 { cell.thirdTimeOption.setTitle(oneResponse.timeOptions[2], forState: .Normal) cell.thirdTimeOption.hidden = false } else { cell.thirdTimeOption.hidden = true } 

或者,如果你像我一样憎恨看到这样的代码重复,你可以枚举这三个button的数组:

 for (index, button) in [cell.firstTimeOption, cell.secondTimeOption, cell.thirdTimeOption].enumerate() { if oneResponse.timeOptions.count > index { button.setTitle(oneResponse.timeOptions[index], forState: .Normal) button.hidden = false } else { button.hidden = true } } 

理论上你可以使用一个出口集合来达到同样的目的,但是我不会在需要遵守订单的时候使用出口集合。

之前我遇到类似的问题。

当你debugging你的程序,这个函数被调用?

如果没有,你需要确保你的ViewController被设置在dataSource委托。 您可以通过按Ctrl +单击TableView,然后将其拖动到视图顶部最左边的黄色圆圈并select“dataSource”,在主要故事板中执行此操作。 这将设置表视图将调用该类中的所有必要的function。 点击并拖动做顶部按钮