我的應用程式使用了 "過濾器 "按鈕,其中whereField查詢是根據按下的過濾器按鈕來完善的。這是一個before過濾的例子。

問題是,當我點擊其中一個行時,它會把我帶到下一個頁面,該頁面對應于我資料庫中屬于該行的原始 indexPath.row。我怎樣才能保留原來的indexPath.row?例如,單元格B始終是indexPath.row = 1,即使在過濾之后。
這是我的第一個視圖控制器的cellForRowAt。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//獲得一個單元格。
let cell = tableView.dequeueReusableCell(withIdentifier: "MealPlanCell", for: indexPath) as! MealPlanCell
//獲得tableView所詢問的膳食計劃。
let mealPlanInTable = mealPlan[indexPath.row] 。
//自定義單元格
cell.displayMealPlan(meanPlanInTable)
//>回傳單元格
return單元格
}
以及我如何在一個單元格被點選后將這個視圖控制器的indexPath.row連接到下一個視圖控制器:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//檢測用戶選擇的indexPath。
let indexPath = tableView.indexPathForSelectedRow
//獲取用戶選擇的膳食計劃
let mealPlanSelected = mealPlan[indexPath!.row] 。
//獲得對NextiewController的參考。
let NextVC = segue. destination as!
//在NextViewController中獲得對currentMealPlanIndex的參考。
NextVC.currentMealPlanIndex = indexPath!.row
}
非常感謝您的任何建議!
uj5u.com熱心網友回復:
你正在從錯誤的陣列中獲取數值。另外,最好是傳遞obj而不是index。
你需要有2個變數--一個用于所有資料&;另一個用于過濾的資料。 在 tableview datasource 中使用過濾的資料變數,并傳遞給 NextVC。
考慮到你的類名是MealPlan。下面是源代碼。
var allMealPlans: [MealPlan]
var filteredMealPlans: [MealPlan]
func onFilterButtonPressed() {
filteredMealPlans = allMealPlans.filter({
//根據你的過濾器在這里回傳真/假。
})
tableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//獲得一個單元格。
let cell = tableView.dequeueReusableCell(withIdentifier: "MealPlanCell", for: indexPath) as! MealPlanCell
//獲得tableView所詢問的膳食計劃。
let mealPlanInTable = filteredMealPlans[indexPath.row] 。
//自定義單元格
cell.displayMealPlan(meanPlanInTable)
//>回傳單元格
return單元格
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//檢測用戶選擇的indexPath。
let indexPath = tableView.indexPathForSelectedRow
//獲取用戶選擇的膳食計劃
let mealPlanSelected = filteredMealPlans[indexPath!.row] 。
//獲得對NextiewController的參考。
let NextVC = segue. destination as!
//在NextViewController中獲取對currentMealPlanIndex的參考。
NextVC.currentMealPlan = mealPlanSelected
}
在你的NextVC中為currentMealPlan添加一個變數
class NextVC。UIViewController {
var currentMealPlan: MealPlan?
}
uj5u.com熱心網友回復:
感謝大家的評論/建議! 我沒有通過indexPath連接視圖控制器中的資料,而是使用了一個與我的視圖控制器之間流動的資料一致的檔案ID。這在我所有的過濾中都有效。
這是我的第一個ViewController:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let indexPath = tableView.indexPathForSelectedRow {
let ingredientsVC = segue.destination as! IngredientsViewController
let documentID = mealPlan[indexPath.row].docID
ingredientsVC.currentMealPlanIndex = indexPath.row
ingredientsVC.passedDocID = documentID!
}
}
而這是在我的第二個ViewController中:
//此變數參考唯一的檔案ID。
var passedDocID = ""
//這就是我如何使用該檔案ID來獲得對相應資料的參考。
let selectedMealPlanIndex = mealPlan.firstIndex(where: {$0.docID == passDocID})
let currentMealPlan = mealPlan[selectedMealPlanIndex! ]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/311734.html
標籤:

