【问题标题】:Reordering cells in UITableView takes out functionality of cells in Swift?在 UITableView 中重新排序单元格会取消 Swift 中单元格的功能?
【发布时间】:2020-04-19 02:33:08
【问题描述】:

我正在使用 JSON 解析来自 Spotify 的数据并将歌曲添加到 UITableView。歌曲播放良好,我添加了删除单元格的功能,但是在添加重新排序单元格的功能时,我无法播放歌曲,也无法滑动删除它们。任何想法,将不胜感激。

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.



    self.tableView.isEditing = true


    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return posts.count

}

这会将专辑图像和歌曲名称添加到 TableView。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
    let mainImageView = cell?.viewWithTag(2) as! UIImageView
    mainImageView.image = posts[indexPath.row].mainImage
    let mainLabel = cell?.viewWithTag(1) as! UILabel
    mainLabel.text = posts[indexPath.row].name
    return cell!
}

这增加了滑动删除功能。

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        posts.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
    } else if editingStyle == .insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
    return .none
}

override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
    return false
}

这增加了重新排序功能。

override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    let movedObject = self.posts[sourceIndexPath.row]
    posts.remove(at: sourceIndexPath.row)
    posts.insert(movedObject, at: destinationIndexPath.row)
    debugPrint("\(sourceIndexPath.row) => \(destinationIndexPath.row)")
    self.tableView.reloadData()
}

【问题讨论】:

  • 尝试在主线程中重新加载tableview。

标签: ios swift xcode uitableview


【解决方案1】:

你不想设置

self.tableView.isEditing = true

在 viewDidLoad 中。这将带您从“正常”模式中选择一个单元格或单元格中的其他元素。设置“self.tableview.isEditing”相当于在许多tableViews的右上角点击一个编辑按钮。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多