我以编程方式删除单元格时出现问题

时间:2017-05-24 08:08:14

标签: ios swift uitableview swift3

我以编程方式在视图控制器中创建了一个tableview,我根本没有使用storyboard。现在我想删除一些单元格,但是发生了一个错误:以NSException类型的未捕获异常终止

任何人都可以帮我解决这个问题吗?

import UIKit

let cellIdentifier = "cellIdentifier"
let headIdentifier = "cellHeader"

class ViewController: UIViewController {

    fileprivate let rect = CGRect(x: 0, y: 0, width: 320, height: 420)
    fileprivate var tableView: UITableView!
    fileprivate let items = ["aaa","bbb","ccc","ddd","eee"]
    fileprivate let titles = ["111","222","333","444","555"]
    fileprivate var folding = false

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        buildUI()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewDidAppear(_ animated: Bool) {
        removeRows()
    }
}

extension ViewController {
    func buildUI() -> () {
        tableView = UITableView(frame: rect)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(TableViewCell.self, forCellReuseIdentifier: cellIdentifier)
        tableView.register(HeadView.self, forHeaderFooterViewReuseIdentifier: headIdentifier)
        self.view.addSubview(tableView)
        print("TableView Created")
    }
}

extension ViewController {
    func removeRows() -> () {
        var indexPaths: [IndexPath] = []

        for i in 0..<tableView.numberOfSections {
            for j in 0..<tableView.numberOfRows(inSection: i) {
                indexPaths.append(IndexPath(row: j, section: i))
                print(indexPaths[i])
            }
        }

        let when = DispatchTime.now() + 2
        DispatchQueue.main.asyncAfter(deadline: when, execute: {
            if self.folding {
                print("show")
            }else {
                //error is here after debug 
                self.tableView.deleteRows(at: indexPaths, with: UITableViewRowAnimation.top) 

                print("hide")
            }
            print("let me go")
        })

    }
}

extension ViewController: UITableViewDelegate, UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return titles.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return items.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = TableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
        cell.textLabel?.text = items[indexPath.row]
        return cell
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let head = HeadView(reuseIdentifier: headIdentifier)
        head.contentView.backgroundColor = UIColor.orange
        head.textLabel?.text = titles[section]
        return head
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
}

这是错误日志:

2017-05-24 16:04:50.509 TableViewDemo2[37957:20126591] *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3600.7.47/UITableView.m:1737
2017-05-24 16:04:50.514 TableViewDemo2[37957:20126591] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (5) must be equal to the number of rows contained in that section before the update (5), plus or minus the number of rows inserted or deleted from that section (0 inserted, 5 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
*** First throw call stack:
(
0   CoreFoundation                      0x000000010f4e5b0b __exceptionPreprocess + 171
1   libobjc.A.dylib                     0x000000010c78d141 objc_exception_throw + 48
2   CoreFoundation                      0x000000010f4e9cf2 +[NSException raise:format:arguments:] + 98
3   Foundation                          0x000000010c3273b6 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 193
4   UIKit                               0x000000010cd9d8e8 -[UITableView _endCellAnimationsWithContext:] + 16362
5   UIKit                               0x000000010cdb49cc -[UITableView _updateRowsAtIndexPaths:updateAction:withRowAnimation:] + 329
6   TableViewDemo2                      0x000000010c1a8a88 _TTSf2n_i___TFFC14TableViewDemo214ViewController10removeRowsFT_T_U_FT_T_ + 568
7   TableViewDemo2                      0x000000010c1a8c87 _TTRXFo___XFdCb___ + 39
8   libdispatch.dylib                   0x000000011043905c _dispatch_client_callout + 8
9   libdispatch.dylib                   0x0000000110415c6e _dispatch_continuation_pop + 1020
10  libdispatch.dylib                   0x000000011042a9fc _dispatch_source_latch_and_call + 230
11  libdispatch.dylib                   0x00000001104234f1 _dispatch_source_invoke + 1167
12  libdispatch.dylib                   0x000000011041a69a _dispatch_main_queue_callback_4CF + 1066
13  CoreFoundation                      0x000000010f4aa909 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 9
14  CoreFoundation                      0x000000010f470ae4 __CFRunLoopRun + 2164
15  CoreFoundation                      0x000000010f470016 CFRunLoopRunSpecific + 406
16  GraphicsServices                    0x00000001113f0a24 GSEventRunModal + 62
17  UIKit                               0x000000010cc5f0d4 UIApplicationMain + 159
18  TableViewDemo2                      0x000000010c1aae27 main + 55
19  libdyld.dylib                       0x000000011048565d start + 1
20  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

0 个答案:

没有答案