滚动时 TableView 滞后

TableView lag when scrolling

滚动时 table 出现滞后。数据库中的图片或长文本没有。对不起,我的英语不好

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("audioCell", forIndexPath: indexPath) as? AudiosTableViewCell

    if cell == nil {
        cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "audioCell") as? AudiosTableViewCell
    } else {
        let realm = try! Realm()
        let audios = realm.objects(Music)[indexPath.row]
        let duration = audios.duration
        var durationString = ""

        if duration/60 < 10 {
            durationString = durationString + "0" }
        durationString = durationString + String(duration/60) + ":"
        if duration%60 < 10 {
            durationString = durationString + "0" }
        durationString = durationString + String(duration%60)

        cell!.artistLabel.text = audios.artist
        cell!.titleLabel.text = audios.title
        cell!.durationLabel.text = durationString
    }
    return cell!
}

如果您需要其他信息,请准确填写您需要的信息。查了很多资料,试了很多方法,第三天很痛苦,还是不行

能否将此代码移到 cellForRow 之外,并确保在 cellForRow 触发之前调用它。

let realm = try! Realm()

这个

    let realm = try! Realm()

应该在 videoDidLoad 或类似的设备上完成,但我建议只有一次

if audios.count == 0 {
        let realm = try! Realm()
        let audios = realm.objects(Music)[indexPath.row]
}

然后替换

    let realm = try! Realm()
    let audiosStore = realm.objects(Music)

let audios = audiosStore[indexPath.row]

当你打电话时

    let realm = try! Realm()

您每次都在请求 Realm 中的所有对象。

tableView.dequeueReusableCellWithIdentifier("audioCell", forIndexPath: indexPath) 从不 returns nil。如果您已经知道单元格将有 class AudiosTableViewCell 您可以重写代码如下:

// Make realm property of your view controller
    let realm: Realm!

// In viewDidLoad
    realm = try! Realm()


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("audioCell", forIndexPath: indexPath) as! AudiosTableViewCell

    let audios = realm.objects(Music)[indexPath.row]
    let duration = audios.duration
    var durationString = ""

    if duration/60 < 10 {
        durationString = durationString + "0" }
    durationString = durationString + String(duration/60) + ":"
    if duration%60 < 10 {
        durationString = durationString + "0" }
    durationString = durationString + String(duration%60)

    cell.artistLabel.text = audios.artist
    cell.titleLabel.text = audios.title
    cell.durationLabel.text = durationString
    return cell
}