[英]Programatically adding sections and cells to Table View Swift
假設我有一個列表/數組的部分:
let sections = [new Section("today", todaylist),
new Section("yesterday", yestlist),
new Section("25th February", list25f),...]
正如您所看到的,每個部分都有一個部分名稱和一個對象列表,這些對象將填充該特定部分中的單元格。
現在,讓我們說這些對象只是簡單的字符串。
我將如何以編程方式循環sections
並創建具有適當標題和適當數量的單元格的新部分。
即 - 部分號的單元格數量。 我會:
sections[i].getList().count
在“今天”的情況下,這相當於
todaylist.count
我無法在故事板中添加部分,因為它會有所不同,表格視圖將是動態的!
謝謝你的幫助 !
看看這段代碼:
import UIKit
class TableViewController: UITableViewController {
var names = ["Vegetables": ["Tomato", "Potato", "Lettuce"], "Fruits": ["Apple", "Banana"]]
struct Objects {
var sectionName : String!
var sectionObjects : [String]!
}
var objectArray = [Objects]()
override func viewDidLoad() {
super.viewDidLoad()
for (key, value) in names {
println("\(key) -> \(value)")
objectArray.append(Objects(sectionName: key, sectionObjects: value))
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return objectArray.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objectArray[section].sectionObjects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
cell.textLabel?.text = objectArray[indexPath.section].sectionObjects[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return objectArray[section].sectionName
}
}
希望它會對你有所幫助。
參考我的舊答案。
您可以使用字典來完成此操作,因為您只處理字符串,它可能很簡單。
例如。
let sections : [String: [String]] = [
"Today": ["list1", "list2", "list3"],
"Yesterday": ["list3", "list4", "list5"]
// and continue
]
和部分使用這個:
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sections.count
}
對於節中的單元格數,可以創建另一個包含節標題的數組
let days = ["Today", "Yesterday", "SomeOtherDays"]
並在numberOfRowsInSection中:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let dayKey = days[section]
if let daylist = sections[dayKey] {
return daylist.count
} else {
return 0
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.