当行返回屏幕时,UITableView 无法保留行顺序,我遇到了一个问题。
向下/向上滚动后,顺序全乱了。索引为 1 的行可能位于第 5 行的位置,依此类推。如何保持行位置不变?
internal func tableView( tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath ) -> UITableViewCell {
var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier( "cell" ) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell" )
// Set the cell's label
cell?.textLabel?.text = "Cell: \(indexPath.row)"
}
// Return the cell
return cell!
}
我做错了什么?
最佳答案
您仅在创建单元格时设置文本(当 dequeueReusableCellWithIdentifier
返回 nil
时)。每次创建或重用单元格时都应设置/更改文本:
internal func tableView( tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath ) -> UITableViewCell {
var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier( "cell" ) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell" )
}
// Set the cell's label
cell?.textLabel?.text = "Cell: \(indexPath.row)"
// Return the cell
return cell!
}
关于ios - TableView 行意外重新排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27018618/