[英]TableView with multiple sections swift
我使用情节提要创建了一个包含两个部分的表格视图。 我希望能够使用数组数组为每个部分显示不同的项目,并能够分别删除每一行。 我尝试了以下操作,但应用崩溃
import Foundation
import UIKit
var letters: [String] = []
class NotificationsViewController: UITableViewController {
var data = [ letters, ["1","2","3"]]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.editing = true
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//return letters.count
return data[section].count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: .Subtitle, reuseIdentifier: "tableCell")
// cell.textLabel?.text = letters[indexPath.row]
cell.textLabel?.text = data[indexPath.section][indexPath.row]
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// // Delete the row from the data source
// letters.removeAtIndex(indexPath.row)
//
// tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
data[indexPath.section].removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
}
这是我的tableViewController: screeshot
错误:
2016-05-10 17:01:48.278 App [70893:6874230] *由于未捕获的异常'NSRangeException'而终止应用程序,原因:'* -[__ NSArrayI objectAtIndex:]:索引1超出范围[0 .. 0]'* **首先抛出调用堆栈:
当我有一个数组(例如字母数组)时,该应用程序运行正常,并且在两个部分中都将显示相同的数据
您可以尝试删除字母并替换数据,如下所示:
var data = [["1","2","3"]]
如果您想要多个部分,例如:
var data = [["1","2","3"], ["4","5"]]
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return data.count
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 20
}
我发现了问题。 这是因为我的表视图中的每个部分都有一行。 添加更多行后,该应用程序开始运行,并且没有崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.