【问题标题】:将数组与 tableView 部分中的核心数据分开
【发布时间】:2022-01-23 10:34:31
【问题描述】:

我正在尝试使用核心数据对我的第一个 TableViewController 中的数组/名称进行排序,以将数据传递给我的第二个 UITableViewController,我已经成功地实现了节数和正确的行数用户需要的每个部分,将玩家数量除以部分数量。

但是,我一直在将每个部分中的玩家数组分开时遇到问题。无法添加模拟器外观的图像,所以我将尝试解释。

用户在第一个 tableView 中输入 10 个名称,然后使用步进器选择团队数量(2 个团队),最后,他们点击团队组合 UIButton,将 10(# 玩家)除以 2(人数团队),所以在第二个 tableView 上,两个 Section 将出现 5 名玩家,但两个 Section 都重复前 5 个名称。

我希望第一个部分显示数组的前 5 个名称,第二个部分显示最后 5 个名称,而不是在每个部分上重复前 5 个名称,无论用户选择每个部分有多少玩家。我已经被困了 4 天,并尝试了循环和扩展,但我找不到其他部分可以在名称数组中间点击的方法,请帮助!谢谢。

这是我的 secondTableView 的代码,我认为问题出在我的 tableView cellForRowAt 或我的 loadedShuffledPlayers() 函数中,

注意:玩家来自核心数据

import UIKit
import CoreData

class TableViewController: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    loadedShuffledPlayers()
    tableView.reloadData()
    
}

var players2 = [Players]()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var numberOfTeams = Int()

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
    return players2.count / numberOfTeams

}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "shuffledNames", for: indexPath)
    cell.textLabel?.text = players2[indexPath.row].names
    return cell
}

func loadedShuffledPlayers(){
    
    let request: NSFetchRequest<Players> = Players.fetchRequest()
    do{
        players2 = try context.fetch(request).shuffled()
    }catch{
        print("Error fetching data .\(error)")
    }
    
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return numberOfTeams
}

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "Team # \(section + 1)"
}

}

【问题讨论】:

    标签: ios arrays swift uitableview core-data


    【解决方案1】:

    问题来了

    cell.textLabel?.text = players2[indexPath.row].names
    

    您只查看行号而忽略了节号。因此,对于 10 和 2 的示例,row 将始终介于 0 和 4 之间。

    所以你需要做类似的事情(未测试):

    let rowsPerSection = players2.count / numberOfTeams
    let rowInSection = indexPath.row + rowsPerSection * indexPath.section
    
    cell.textLabel?.text = players2[rowInSection].names
    

    【讨论】:

    • 非常感谢!!这完全符合我的预期,你让@Joakim 很容易理解
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多