Swift: cellForRowAtIndexPath not called in the ord

2019-09-22 04:56发布

问题:

At first the indexpath are called in sequence of 0,1,2... but after clicking on the table view , the func tablview is called with indexpath that seems completely random , and hence i am unable to reproduce the same data . I am using array to correlate the rows of the table .

The code is here:

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}


override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return  myList.count
}
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
// Configure the cell...

    println("table view --> ")
    let CellID : NSString = "Cell"
    var cell : UITableViewCell = tableView?.dequeueReusableCellWithIdentifier(CellID)as UITableViewCell
     var VehicleName = cell.viewWithTag(1) as UILabel
     var VehicleNumber = cell.viewWithTag(2) as UILabel

     if let ip = indexPath
     {

        VehicleName.text = arrayData[ip.row*2];
        VehicleNumber.text = arrayData[ip.row*2+1];
    }
 }
     return cell

 }

回答1:

You have a design problem. You need to be able to supply the data as requested in a random access fashion.

Study the documentation on UITableView and `UITableViewDataSource'.

The API calls cellForRowAtIndexPath as it needs the data, it just requests the data that it needs to display, not all the data each time. It only creates the cells that are being displayed. If you had 1000 rows of data and were displaying rows 900 through say 903 it only needs that data. If the view scrolls to display one more row it only needs more data from row 904.



回答2:

There is absolutely no guarantee in what order of indexPaths cellForRowAtIndexPath gets called. It is upon the UIKit framework.

You need to, and can, fully control how your data source array holds data. In this case, it is arrayData - I also have a feeling that this is in some way related to myList, but it is not visible from your code snippet. Work on how elements are arranged within arrayData and then you will have expected elements in all cells.