【发布时间】:2020-11-24 01:21:36
【问题描述】:
我是一名新开发人员,我有一个带有类别集合视图的金融应用程序。
当用户点击一个类别时,下一页应填充主类别的子类别的集合视图。
这是我当前的数据模型:
import UIKit
struct Category {
var name: String
var color: UIColor
var amountBudgeted: Double
var subCategories: [SubCategory]
}
struct SubCategory {
var name: String
var amountBudgeted: Double
}
let categories = [
Category(
name: "Income",
color: UIColor(rgb: Constants.green),
amountBudgeted: 0.00,
subCategories: [
SubCategory(name: "Paycheck", amountBudgeted: 0.00),
SubCategory(name: "Bonus", amountBudgeted: 0.00),
SubCategory(name: "Dividend", amountBudgeted: 0.00),
SubCategory(name: "Rental Income", amountBudgeted: 0.00),
]),
Category(
name: "Housing",
color: UIColor(rgb: Constants.grey),
amountBudgeted: 0.00,
subCategories: [
SubCategory(name: "Mortgage", amountBudgeted: 0.00),
SubCategory(name: "Property Tax", amountBudgeted: 0.00),
SubCategory(name: "HOA Fees", amountBudgeted: 0.00),
SubCategory(name: "Household Repairs", amountBudgeted: 0.00),
]),
Category(
name: "Transportation",
color: UIColor(rgb: Constants.red),
amountBudgeted: 0.00,
subCategories: [
SubCategory(name: "Car Payment", amountBudgeted: 0.00),
SubCategory(name: "Gas", amountBudgeted: 0.00),
SubCategory(name: "Car Repairs", amountBudgeted: 0.00),
SubCategory(name: "Registration", amountBudgeted: 0.00),
]),
Category(
name: "Food",
color: UIColor(rgb: Constants.yellow),
amountBudgeted: 0.00,
subCategories: [
SubCategory(name: "Groceries", amountBudgeted: 0.00),
SubCategory(name: "Restaurants", amountBudgeted: 0.00),
]),
]
我可以像cell.nameLabel.text = categories[indexPath.item].name 一样轻松地调用 cellForItemAt 中的主要类别属性,但我无法让子类别视图工作。
我正在尝试cell.nameLabel.text = categories[indexPath.item].subCategories[indexPath.item].name,但无法正常工作。
我还需要弄清楚如何在视图控制器之间关联数据,但这可能需要成为一个单独的问题。
我需要重新考虑我的数据模型吗?还是我需要以不同的方式设置 cellForItemAt 方法?
谢谢。
【问题讨论】:
-
问题是当您点击类别时,您无法访问新视图中的子类别?
-
是的,我不知道如何关联数据,以便当用户点击某个类别时,它会填充子类别数据。
-
我认为您的代码应该可以正常工作,您的模型定义没有问题,无论它看起来非常好,所以我猜测错误可能在于您如何将数据发送到下一个视图,您应该确保您发送的对象已填充并且您可以访问其字段
-
您应该将整个子类别数组
subCategories发送到下一个视图控制器,而不仅仅是一个。如果您需要有关如何在视图控制器之间传递数据的信息,请参阅this question
标签: swift struct categories datamodel