首页 > 解决方案 > 如何使用 UITableView 在列表中创建列表

问题描述

我有一个要求。我必须在哪里获取学生名单,然后我必须显示他们注册的科目。

例子

现在您可以在下面看到我的学生列表,即 Student1、student2 等等。每个学生都有不同数量的科目 在此处输入图像描述

到目前为止我做了什么:

我创建了一个包含标签和空垂直堆栈视图的自定义单元格。

然后在方法tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)我正在运行 for 循环,动态生成一些 UiLabel 并将它们添加到垂直堆栈视图中

问题: 通过这样做,我得到了我想要的。但是当我向上和向下滚动时,for循环会在每次向上/向下滚动时一次又一次地重复单元格中的数据

如果有任何其他方法可以做到这一点,请提供帮助。

标签: iosuitableview

解决方案


您可以将 tableview 与部分一起使用。

  1. 在部分中设置学生姓名
  2. 在单元格中设置您的主题

这是带有部分的 tableview 示例。 https://blog.apoorvmote.com/uitableview-with-multiple-sections-ios-swift/

这是示例代码,仅供您参考。

class TableViewController: UITableViewController {

let section = ["pizza", "deep dish pizza", "calzone"]

let items = [["Margarita", "BBQ Chicken", "Pepperoni"], ["sausage", "meat lovers", "veggie lovers"], ["sausage", "chicken pesto", "prawns", "mushrooms"]]
// MARK: - Table view data source

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

return self.section\[section\]

}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
 // #warning Incomplete implementation, return the number of sections

return self.section.count

}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
 // #warning Incomplete implementation, return the number of rows

return self.items\[section\].count

}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
 let cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath)

// Configure the cell...

cell.textLabel?.text = self.items[indexPath.section][indexPath.row]

return cell

}

更新

自定义剖面视图创建自定义视图并将视图显示为剖面

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

    let view = UIView(frame: CGRect(x:0, y:0, width:tableView.frame.size.width, height:18))
    let label = UILabel(frame: CGRect(x:10, y:5, width:tableView.frame.size.width, height:18))
    label.font = UIFont.systemFont(ofSize: 14)
    label.text = "This is a test";
    view.addSubview(label);
    view.backgroundColor = UIColor.gray;
    return view

}

自定义部分的示例代码

更新 2

带有单元格引用的自定义标题

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let  headerCell = tableView.dequeueReusableCellWithIdentifier("HeaderCell") as! CustomHeaderCell
    headerCell.backgroundColor = UIColor.cyanColor()

    switch (section) {
    case 0:
      headerCell.headerLabel.text = "Student Name 1";
      //return sectionHeaderView
    case 1:
      headerCell.headerLabel.text = "Student Name 2";
      //return sectionHeaderView
    case 2:
      headerCell.headerLabel.text = "Student Name 3";
      //return sectionHeaderView
    default:
      headerCell.headerLabel.text = "Other";
    }

    return headerCell
  }

推荐阅读