ios - TableView 行意外重新排序

标签 ios swift uitableview

当行返回屏幕时,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/

相关文章:

iphone - 关于JSONKit analyze的问题

ios - 在 Swift 中迭代 NSLayoutConstraints 会出现 "[AnyObject] does not have a member named ' Generator'"错误

ios - 如何以编程方式在 UITableViewCell 中添加 UIView?

ios - 如果在 tableview iOS 中找不到数据,则无法在中心显示 View ?

ios - 如何知道使用 MapKit 的异步搜索何时完成

ios - 哪个是抑制 "unused variable"警告的最佳方法

android - 如何在 iOS 中使用 WSSE 和 salted sha512 超过 1 次迭代

swift - 在自定义单元格中使用 UISwitch 设置对象属性

php - 基于图像的 TableView 的后端数据库

iphone - UITableView单元格高度设置生命周期