表视图单元格添加说明第 0 节中的行数无效

tableview cell addition stating invalid number of rows in section 0

每次我点击添加按钮单元格。当用户点击添加按钮时,应该立即将一个新单元格添加到表视图中,整个代码将进入运行时错误。我想修复错误,以便您可以将单元格添加到表格视图。运行时错误状态

"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 (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out)."

import UIKit
 

 
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
 
    

    var addBTN = UIButton()
    var arr = [1,1,3,3]
    var currentIndex = 0
    var arrayValues = [Int]()
    
   
    

 
    var pic = UIImageView()
    var addBtn = UIButton()
    var cellCount = 5
    var tableview = UITableView()

    
    
    

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cellCount // use a variable here so you can change it as you delete cells, else it will crash
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 118
    }
   
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomTv
        
   
        return cell
    }
    

    
  
    
    override func viewDidLoad() {
        super.viewDidLoad()
     
        [addBTN].forEach{
            [=10=].translatesAutoresizingMaskIntoConstraints = false
            view.addSubview([=10=])
        }
        tableview.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height * 0.8)
        addBTN.frame = CGRect(x: view.frame.width / 2, y: view.frame.height * 0.8, width: view.frame.width / 2  , height: view.frame.height / 5)
        addBTN.backgroundColor = .systemTeal
      
        view.addSubview(tableview)

 
        tableview.register(CustomTv.self, forCellReuseIdentifier: "cell")
        tableview.delegate = self
        tableview.dataSource = self
        pic.isHidden = true
        pic.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height )
        
      
        addBTN.addTarget(self, action: #selector(newCell), for: .touchDown)
        
        
        addBTN.setTitle("New cell", for: .normal)
    }
    @objc func newCell(){
        
        arr.append(6) /// not sure what the numbers mean though...
        tableview.beginUpdates()
        tableview.insertRows(at: [IndexPath(row: arr.count - 1, section: 0)], with: .automatic) /// animate the insertion
    tableview.endUpdates()

    }
    
}



protocol CustomTvCellDelegateadd: AnyObject {
    func addCeller(_ customTV: CustomTv)
}
class CustomTv: UITableViewCell { // it's good form to Pascal case your class name ;)
    
    weak var delegate: CustomTvCellDelegate? // make that delegate a property of your cell
    weak var delegatef: CustomTvCellDelegateadd?
    lazy var backView : UIView = {
        let view = UIView(frame: CGRect(x: 10, y: 6, width: self.frame.width  , height: 110))
        view.backgroundColor = .green
        
        return view
    }()



        lazy var pic : UIImageView = {
            let btn = UIImageView(frame: CGRect(x: 50-25, y: 6, width: 100 , height: 110))
            btn.backgroundColor = .systemPink
    
            return btn
    
        }()


    override func layoutSubviews() {
        backView.clipsToBounds = true
        backView.frame =  CGRect(x: 0, y: 6, width: bounds.maxX  , height: 110)
        
        // moved these calls here instead of on setSelected(_selected:animated:)
        addSubview(backView)
       

        backView.addSubview(pic)
        
        

        
 
      
    }
        @objc func addButtonTapped() {
            self.delegatef?.addCeller(self)
        }
}

那是因为您将一个值 (6) 附加到名为 arr 的数组,但是当 tableView 要求您 returned cellCount 部分中的行数时,您从来没有费心增加它,所以它会继续至 return 5.

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cellCount // use a variable here so you can change it as you delete cells, else it will crash
    }

所以当执行 tableview.insertRows 时,tableView 期望行数增加数组中元素的数量(在您的情况下,它期望行数为 6,但由于 [=13 的值不变=] 它只会得到 5 因此 tableView 不知道并抛出错误提及

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 (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out)."

所以要么改变

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arr.count
    }

或使用

@objc func newCell(){
        cellCount += 1 // update the value
        arr.append(6)
        tableview.beginUpdates()
        tableview.insertRows(at: [IndexPath(row: arr.count - 1, section: 0)], with: .automatic) /// animate the insertion
    tableview.endUpdates()

}

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

以你觉得更有意义的为准:)