我在我的tableView上工作,剛纔我實現了刪除行的功能,但是在刪除了一行後,應用程序崩潰並顯示此錯誤(致命錯誤:索引超出範圍)Swift錯誤:索引超出範圍
struct User {
var name: String
var images: UIImage
var coordinate : (Double , Double)
var type: String
var address: String
}
var users = [User]()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
rows = 0
tableView.reloadData()
insertRowsMode3()
}
@IBAction func refreshTapped(_ sender: Any) {
rows = 0
tableView.reloadData()
insertRowsMode3()
}
func insertRowsMode2() {
for i in 0..<users.count {
insertRowMode2(ind: i, usr: users[i])
}
}
func insertRowMode2(ind:Int,usr:User) {
let indPath = IndexPath(row: ind, section: 0)
rows = ind + 1
tableView.insertRows(at: [indPath], with: .right)
}
func insertRowsMode3() {
rows = 0
insertRowMode3(ind: 0)
}
func insertRowMode3(ind:Int) {
let indPath = IndexPath(row: ind, section: 0)
rows = ind + 1
tableView.insertRows(at: [indPath], with: .right)
guard ind < users.count-1 else { return }
DispatchQueue.main.asyncAfter(deadline: .now()+0.20) {
self.insertRowMode3(ind: ind+1)
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rows
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell
let user = users[indexPath.row]
cell.selectionStyle = .none
cell.myImage.image = user.images
cell.myLabel.text = user.name
cell.myTypeLabel.text = user.type
return (cell)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
UIView.animate(withDuration: 0.2, animations: {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell
})
performSegue(withIdentifier: "goToLast" , sender: users[indexPath.row])
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete {
users.remove(at: indexPath.row)
tableView.reloadData()
}
}
這是我的tableView的代碼,我想我知道爲什麼應用程序在走,但崩潰我不知道如何解決這個問題的一部分,我可以做什麼?
和 更新刪除代碼喜,在這條線,在哪裏呢VaR的用戶來自users.remove(在:indexPath.row)? –
在'numberOfRowsInSection'而不是'返回rows'回報'返回users.count'。手動計算行數很容易出錯。 – vadian
@ S.Wei對!我編輯了這個問題 – bero