随机化表格视图单元格的内容

问题描述 投票:0回答:1

我下面的代码是从名为 title 的核心数据加载字符串的代码。我想做的是有一个函数,可以随机化每次按下按钮时所有名称在表格视图单元格上显示的顺序。如果可能的话,也保存新订单。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let song = songs[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "songCell", for: indexPath) as UITableViewCell
        cell.textLabel?.text = song.title
        return cell
    }
arrays swift uitableview random core-data
1个回答
0
投票
  1. 创建一个函数,随机化

    songs
    数组的顺序,然后重新加载表视图以反映新顺序。

  2. 在按下按钮时触发的函数中,调用随机化函数并将新订单保存回数据存储。

以下是如何在代码中实现此功能的示例:

class YourViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    // Assuming this is your songs array
    var songs: [Song] = []
    
    // ... other code
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let song = songs[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "songCell", for: indexPath) as UITableViewCell
        cell.textLabel?.text = song.title
        return cell
    }
    
    // Function to randomize the order of songs array
    func randomizeSongsOrder() {
        songs.shuffle()
        tableView.reloadData()
    }
    
    // IBAction for the button
    @IBAction func shuffleButtonPressed(_ sender: UIButton) {
        randomizeSongsOrder()
        
        // Save the new order back to your data store (Core Data)
        // You need to implement this part based on your Core Data setup
    }
}

在上面的代码中,

randomizeSongsOrder
函数使用
songs
方法对
shuffle
数组进行打乱,然后重新加载表格视图。当按下随机播放按钮时,您可以调用此函数来随机化歌曲的顺序,并根据需要将新顺序保存回您的数据存储(核心数据)。

© www.soinside.com 2019 - 2024. All rights reserved.