tableView didset不会重新加载

时间:2019-08-23 11:30:11

标签: tableview reload

无论何时调用didset为countRow,我都试图重新加载tableview。它从未成功。

我已经尝试过后卫,如果让他进入防守端,那将永远无法解决。 我意识到它正在调用tableview的另一个对象。太奇怪了,

导入UIKit

ViewController类:UIViewController,UITableViewDelegate,UITableViewDataSource {

// Global Variable
var tableView: UITableView!
var tableView2 : UITableView!


var countRow : Int = 0  {
    didSet{


        //if let tableview  == tableview
         guard tableView2 == tableView else

        {

            tableView2 = UITableView(frame: self.view.bounds)
            tableView2.delegate = self
            tableView2.dataSource = self
           self.tableView2.reloadData()
            self.tableView.reloadData()
                print ("3countRow: \(countRow)")
            return
        }

        self.tableView2.reloadData()
        self.tableView.reloadData()
        print ("2countRow: \(countRow)")

    }

}

override func viewDidLoad() {
    super.viewDidLoad()



    tableView = UITableView(frame: self.view.bounds)
    tableView.delegate = self
    tableView.dataSource = self
    self.view.addSubview(tableView)
    tableView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)



    tableView.register(TableViewCell.self, forCellReuseIdentifier: "TableViewCell")
    tableView.register(AppCell.self, forCellReuseIdentifier: "NormalCell")
    tableView.register(appDays.self, forCellReuseIdentifier: "textField")
    tableView.reloadData()


}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    tableView.reloadData()

}



func numberOfSectionsInTableView(tableView: UITableView) -> Int {


    return 3
}

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

print (countRow)
    return 5 + countRow


}


func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 80

}




func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


    if indexPath.row == 0
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "NormalCell", for: indexPath) as! AppCell
        cell.backgroundColor = UIColor.groupTableViewBackground
        return cell
    }

    if indexPath.row == 1 || indexPath.row == 2
    {
    var cell: TableViewCell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
    cell.backgroundColor = UIColor.groupTableViewBackground
    return cell
    }

   let cell = tableView.dequeueReusableCell(withIdentifier: "textField", for: indexPath) as! appDays
    cell.backgroundColor = UIColor.groupTableViewBackground
    return cell



}

}

计数将被打印在程序中

1 个答案:

答案 0 :(得分:0)

您永远不会将countRow设置为一个值。您只添加5 + countRow,并不意味着您在countRow中设置了5。

  存储新值后立即调用

didSet。 Swift official documentation