为什么我不能在我的数组中添加标签?

时间:2017-03-16 03:45:39

标签: ios swift

我从变量中的datePicker获取dateChanged的值,然后将该变量追加到我的String数组中。然后我将StringArray打印到我的TableView单元格中,但我无法弄清楚它为什么不起作用。这是我将时间声明为全局变量的代码:

    var time: [String] = []

    func datePickerValueChanged(sender:UIDatePicker) {

    let dateFormatter = DateFormatter()

    dateFormatter.dateStyle = DateFormatter.Style.short

    dateFormatter.timeStyle = DateFormatter.Style.short

    let mydate="adding reminder on \(dateFormatter.string(from: sender.date))"

    time.append(mydate)
  }

然后我尝试用代码打印我的TableViewCell中的值:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCellID") as! CustomCell
cell.dateLabel?.text=time[indexPath.row]
return (cell)

这是我的CustomCell类的代码:

class CustomCell: UITableViewCell {

@IBOutlet weak var dateLabel: UILabel!
override func awakeFromNib() {
    super.awakeFromNib()
} 
  override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

 }
}

Here is the error

2 个答案:

答案 0 :(得分:1)

numberOfRowsInSection方法返回list.count

并在cellForRowAt indexPath

cell.dateLabel?.text = time.indices.contains(indexPath.row) ? time[indexPath.row] : "Not Available"

答案 1 :(得分:0)

请修改代码中的这些行并进行测试。

override func tableView(_ tableView: UITableView, numberOfRowInSection section: Int) -> Int {
    //other lines you want
    return time.count //Not get index out of range error
}

你返回list.count但不返回time.count。如果列表数组小于时间,则可能是可能的,因此可以索引超出范围。