如何在同一个表格视图中显示两个不同的表格视图单元格,总是成对出现?

时间:2019-05-07 22:39:30

标签: ios swift uitableview tableview

我想将两个不同的tableViewCells放在同一个tableView中,以便它们总是成对出现。第一个tableViewCell应该显示可由用户调整的开始时间和结束时间。 (也许是datePicker)第二个tableViewCell应该显示一个textField,它也是可编辑的。两个tableViewCells都应该有一个小按钮,可以选择是否勾选。我想将该数据(时间,文本,按钮状态)存储在某个地方。

我将两个单元格的结构都设置为dataType,并创建了一个数组。我还设置了cellForRowAt,但是在运行应用程序时出现错误。

要创建数据类型:

struct ScheduleCell{

    var id: Int
    var buttonState: Bool
    var text: String
    var time01: String
    var time02: String

}

存储数据的地方:

var scheduleCellEntries: [ScheduleCell]! = [ScheduleCell(id: 2, buttonState: false, text: "Test", time01: "12:30", time02: "12:20"), ScheduleCell(id: 2, buttonState: false, text: "Test", time01: "12:30", time02: "12:20"), ScheduleCell(id: 2, buttonState: false, text: "Test", time01: "12:30", time02: "12:20"), ScheduleCell(id: 2, buttonState: false, text: "Test", time01: "12:30", time02: "12:20")]

分配行数:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        var count: Int?

        if tableView == scheduleTableView{
            count = scheduleCellEntries.count * 2

        }
    return count!
}

将数据提取到单元格中

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if tableView == scheduleTableView {

            if indexPath.row % 2 != 0{
                let cell = tableView.dequeueReusableCell(withIdentifier: "scheduleCell", for: indexPath) as! scheduleTableViewCell
                cell.scheduleTextField.text = scheduleCellEntries[indexPath.row].text


        return cell
}else{
        let cell = tableView.dequeueReusableCell(withIdentifier: "scheduleDateCell", for: indexPath) as! ScheduleDateTableViewCell


        return cell
}

运行应用程序时,出现以下错误Thread 1: Fatal error: Index out of range

1 个答案:

答案 0 :(得分:0)

问题是,scheduleCellEntries中的记录数为X,但返回scheduleCellEntries.count * 2后,表中单元格的数目为两倍。在cellForRowAt中,应该使用indexPath.row而不是scheduleCellEntries来访问indexPath.row / 2中的数据,因此,当表向第0行和第1行询问数据时,将选择相同的数据。

我更改了一些示例代码,添加了具有适当索引的变量以获取数据let indexOnData = indexPath.row / 2,并将其用于scheduleCellEntries

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if tableView == scheduleTableView {
        let indexOnData = indexPath.row / 2
        if indexPath.row % 2 != 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "scheduleCell", for: indexPath) as! scheduleTableViewCell
            cell.scheduleTextField.text = scheduleCellEntries[indexOnData].text
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "scheduleDateCell", for: indexPath) as! ScheduleDateTableViewCell

        }
        return cell
    }
}