你對什麼是類型和什麼是價值感到困惑。您已經定義了四種類型,但您需要的是兩種類型,以及這些類型的一些實例(值)。
這裏有您需要的類型:
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
}
}
不錯!讓我們走吧! – petaire