【发布时间】:2019-05-07 22:39:29
【问题描述】:
我想将两个不同的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!
【问题讨论】:
-
您将
count * 2作为行数返回是正确的,但是当您访问数组时,您需要将row除以2,否则您尝试访问的索引不会不存在。就我个人而言,我会创建一个包含所有必需 UI 元素的单元格,而不是尝试创建两个单元格。 -
使用您需要显示的数据创建一个 ScheduleCell。因为 numberOfRowsInSection 无法猜测您要做什么。如果它与某个参考值匹配,您将显示它,然后您可以更改 tableviewcell 演员表
-
为什么将数据分成 2 个单元格很重要?如果这些单元格总是组合在一起,我建议创建一个包含所有必要元素的单元格。在这种情况下,您将拥有 numberOfRowsInSection = scheduleCellEntries.count
标签: ios swift uitableview tableview