繁体   English   中英

以编程方式将部分和单元格添加到Table View Swift

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM