以编程方式向Swift表格视图添加部分和单元格

6

假设我有一个部分列表/数组:

let sections = [new Section("today", todaylist), 
                new Section("yesterday", yestlist), 
                new Section("25th February", list25f),...]

正如您所见,每个部分都有一个部分名称和一个对象列表,它将填充该特定部分内的单元格。
现在,假设这些对象只是简单的字符串。
我该如何通过编程方式循环遍历“sections”,并创建具有适当标题和适当数量单元格的新部分。
即-第i节的单元格数应为:
sections[i].getList().count

在“今天”的情况下,这相当于:
todaylist.count

我无法在故事板中添加部分,因为它会变化,表视图将是动态的!

感谢任何帮助!


请查看此链接:http://blog.adambardon.com/tableview-with-many-sections-and-items-from-array/ - Adam Bardon
2个回答

22

看看这段代码:

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
    }
}

希望这能对你有所帮助。

参考自我的回答。


非常感谢,代码非常易懂。有一个问题...在这一行 tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) 中,我只需要在Storyboard中创建一个ID为“cell”的原型单元格吗? - Greg Peckory
因为这似乎给我一个错误,而且这是我能想到的全部。 - Greg Peckory
点击您的单元格,进入属性检查器并将标识符添加为cell。 - Dharmesh Kheni
有点尴尬,我使用了错误的恢复 ID。非常感谢你的精彩回答! - Greg Peckory
1
它不遵循数组顺序,对象以随机顺序附加。 - shubh14896

1
你可以通过使用字典来实现,因为你只是在处理字符串,这可能很简单。
例如:
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
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接