我不确定我在这里做的是最好的设计......
我正在编写一个应用程序,其中有章节类别嵌套章节。所有值都将被硬编码。例如:
struct Chapter1 {
struct Category1{
let name = "#1"
let content = "Lorem Ipsum"
}
struct Category2{
let name = "#2"
let content = "Lorem Ipsum Ipsum"
}
struct Category3{
let name = "#3"
let content = "Ipsum Lorem Ipsum"
}
}
现在的问题是,我想在 numberOfSectionsInTableView 中返回类别的数量。我怎么算那些?有办法吗?或者也许我的设计不正确?
然后,我需要通过 segue 传递结构名称……这可能吗?
目前,我找到的解决方案非常不优雅。在 Chapter1 结构中,我放置了一个包含“Category1”、“Category2”等的数组……这不是最佳选择!而且我没有找到解决方案来做到这一点:
var x = "Category1"
var nameOfTheSelectedCategory = Chapter1.x.name
甚至不知道这是否可能,但它可能是一个解决方案......我也尝试过使用开关,但我遇到了同样的问题......
谢谢!
最佳答案
你对什么是类型,什么是值感到困惑。您已经定义了四种类型,但您需要的是两种类型,以及这些类型的一些实例(值)。
以下是您需要的类型:
struct Chapter {
let categories: [Category]
}
struct Category {
let name: String
let content: String
}
这里是一个数组值,其中包含一个 Chapter
类型的值,其中包含三个 Category
类型的值:
let chapters: [Chapter] = [
Chapter(categories: [
Category(name: "Data Structures", content: "structs, classes, enums, tuples, etc."),
Category(name: "Algorithms", content: "sorting, searching, calculating, etc."),
Category(name: "Programs", content: "Flappy Bird, Microsoft Word, etc."),
])
]
您可以像这样定义 TableView 数据源:
class MyDataSource: NSObject, UITableViewDataSource {
let chapters: [Chapter] = [
Chapter(categories: [
Category(name: "Data Structures", content: "structs, classes, enums, tuples, etc."),
Category(name: "Algorithms", content: "sorting, searching, calculating, etc."),
Category(name: "Programs", content: "Flappy Bird, Microsoft Word, etc."),
])
]
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return chapters.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return chapters[section].categories.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CategoryCell", forIndexPath: indexPath) as! CategoryCell
let category = chapters[indexPath.section].categories[indexPath.row]
cell.category = category
return cell
}
}
如果 segue 连接到 Storyboard中的单元格之外,那么单元格本身就是发送者,因此您可以这样处理:
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "CategoryDetail" {
let cell = sender as! CategoryCell
let categoryDetailViewController = segue.destinationViewController as! CategoryDetailViewController
categoryDetailViewController.category = cell.category
}
}
关于ios - 计算嵌套在另一个结构中的结构数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35830165/