Swift:将包含自定义标签的单元格添加到 UITableView

标签 swift uitableview

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

我找到的所有示例要么是 +30 行,要么不起作用... 我正在使用 swift 4 和 UIKit。

最佳答案

  1. 在 Xcode 中,使用“File > New > File > Cocoa Touch Class”。
  2. 使用UITableViewController作为基类
  3. 你会发现一个很大的模板,只需执行:

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

      注意:要实现 tableView(_:cellForRowAt:),您必须在 Storyboard中注册一个单元格,并在此函数中使用它的名称。或者使用 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
}

关于Swift:将包含自定义标签的单元格添加到 UITableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48787275/

相关文章:

swift - 数据未显示在 TableView Swift CoreData 中

objective-c - UITableView 单击

ios - 单击时以编程方式生成的按钮使应用程序崩溃。

swift - 如何使用 multipartFormData 和参数上传图像,使用 Alamofire 4.3 请求所需的身份验证

ios - 导入json文件到对象错误

ios - UITable,如何在 Swift IOS 中将委托(delegate)分配给 UITable

ios - 在 UIRefreshControl 上自动调用 cellForRowAtIndex

ios - 实现 swift equatable 协议(protocol)给我错误的访问错误。为什么?

swift - 在 Swift 中使用 loadHTMLString 时遇到问题

ios - 如何从 json 响应创建动态节头