我不确定我在这里做最好的设计......
我正在编写一个应用程序,其中我有各种章节嵌套章节。所有值都将被硬编码。例如:
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中返回Category的数量。我怎么算那些?有办法吗?或许我的设计不合适?
然后,我需要通过segue传递结构名称......是否可能?
目前,我发现的解决方案非常不优雅。在Chapter1结构中,我放置了一个带有“Category1”,“Category2”等的数组......这不是最佳的!我没有找到解决办法:
var x = "Category1"
var nameOfTheSelectedCategory = Chapter1.x.name
甚至不知道是否可能,但它可能是一个解决方案......我也试过一个开关,但我遇到了同样的问题......
谢谢!
答案 0 :(得分:3)
您对什么是类型以及什么是值感到困惑。您已经定义了四种类型,但您需要的是两种类型,以及这些类型的一些实例(值)。
以下是您需要的类型:
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."),
])
]
您可以像这样定义表视图数据源:
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已连接到故事板中的单元格之外,那么单元格本身就是发件人,因此您可以像这样处理它:
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
}
}
答案 1 :(得分:0)
我认为你应该考虑稍微改变一下你的数据模型,看看做这样的事情
class Chapter {
let name: String
var sections: [Category]
init(name: String, sections: [Category]){
self.name = name
self.sections = sections
}
}
struct Category {
let name: String
let content: String
}
var newChapter = Chapter(name: "One", sections: [Category(name: "#1", content: "Lorem Ipsum")])
newChapter.sections.append(Category(name: "#2", content: "Test"))
如果您需要通过self.data = [Chapter]
然后在numberOfSectionsInTableView
返回self.data.count
和numberOfRowsInSection
返回self.data[section].sections.count
来支持多个章节,则可以进一步扩展您的模型