【问题标题】:Swift: Add cells containing a custom label to an UITableViewSwift:将包含自定义标签的单元格添加到 UITableView
【发布时间】:2018-02-14 12:30:03
【问题描述】:

如何以编程方式将单元格添加到 UITableview 并使用来自myArray[cellNumber] 的数据填充单元格。 数组中的数据是字符串类型。 tableview 只是一个与 outlet 连接的 UITableView。

我发现的所有示例都是 +30 行或不起作用... 我正在使用 swift 4 和 UIKit。

【问题讨论】:

标签: swift uitableview


【解决方案1】:
  1. 在 Xcode 中,使用“File > New > File > Cocoa Touch Class”。
  2. 使用UITableViewController 作为基类
  3. 你会发现一个大模板,只需实现:

    • numberOfSections(in tableView: UITableView) -> Int,让它返回 1。你现在只需要一个部分。
    • tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int,让它返回你的数组的大小
    • override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell。取消注释,实现它。

      注意:要实现 tableView(_:cellForRowAt:),您必须在情节提要中注册一个单元格,并在此函数中使用其名称。或者使用register(_:forCellReuseIdentifier:) 以编程方式注册一个单元格。

这里有更全面的指南iOS Getting Started Guide UITableView

实现示例:

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1  // Only one section
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return myArray.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // "cell" is registered in the Storyboard
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    // The registered cell, has a view with tag 1 that is UILabel as an example
    // IndexPath is a data structure that has "section" and "row"
    // It located the cell in your tableview/collectionview
    (cell.viewWithTag(1) as? UILabel)?.text = myArray[indexPath.row]

    return cell
}

【讨论】:

    【解决方案2】:

    1.你的ViewController必须符合UITableViewDelegate、UITableViewDataSource。 这意味着你的类文件看起来像这样

    class MyCustomViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
    

    2.您必须将 UITableView 对象的 dataSource 和 delegate 属性分配给 viewController,可以通过拖动从 Storyboard 中分配,也可以在 viewDidLoad 中的代码中,例如通过键入:

    myTableView.delegate = self
    myTableView.dataSource = self
    

    3.您的类必须覆盖 UITableView 所需的委托/数据源方法 numberOfRowsInSection 和 cellForRowAt:

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = myArray[indexPath.row]
        return cell
    }
    

    请注意,要使用 dequeReusableCell,您必须为情节提要文件中的单元格设置重用标识符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多