我正在嘗試從我的第一個TableViewController使用核心資料對陣列/名稱進行排序以將資料傳遞給我的第二個UITableViewController,我已經成功地通過劃分用戶需要的每個部分實作了部分的數量和正確的行數玩家人數同段數。
但是,我在將每個部分中的玩家陣列連續分開時遇到了問題。無法添加模擬器的影像,所以我會嘗試解釋。
用戶在第一個 tableView 中輸入 10 個名稱,然后使用步進器選擇團隊數量(2 個團隊),最后,他們單擊UIButton將 10(# 個玩家)除以 2(團隊數量)的團隊,依此類推tableView 兩個部分將出現 5 個玩家,但兩個部分都重復前 5 個名稱。
我希望第一個部分顯示陣列的前 5 個名稱,第二個部分顯示最后 5 個名稱,而不是在每個部分重復前 5 個名稱,無論用戶選擇每個部分的玩家數量。我已經被卡住了 4 天,并嘗試了回圈和擴展,但我找不到其他部分的方法來點擊名稱陣列的中間,請幫助!!謝謝。
這是我的 secondTableView 的代碼,我認為問題出在我的 tableViewcellForRowAt或我的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)"
}
}
uj5u.com熱心網友回復:
問題就在這里
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/390701.html
