背景 我有一个可以接收实时数据流的 IOS 应用程序。我已经实现了自定义值对象来存储/捕获实时流中的这些数据。我现在需要将我的自定义数据对象绑定(bind)到 UI(主要使用调用这些自定义对象值的表格 View 和自定义单元格)。
问题 如何使用 Bond、ReactiveKit 或 Swift 3 中的其他框架将一组自定义对象值绑定(bind)到我的 UI?
示例代码
public class Device {
var name: String
var status: String
}
public class DeviceController {
var devices = Array<Device>()
// more code to init/populate array of custom Device classes
}
public class CustomViewController: ... {
var deviceController = DeviceController()
var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// more code to register custom cell
}
public class CustomCell:UITableviewCell {
@IBOutlet weak var deviceName: UILabel!
@IBOutlet weak var deviceStatus: UILabel!
}
最佳答案
您使用委托(delegate)模式,该模式已经为包括 UITableView 在内的许多 UIKit 元素设置。
一个UITableView有两个属性,可以是任何符合两个协议(protocol)的对象,具体来说
var dataSource: UITableViewDataSource?
var delegate: UITableViewDelegate?
因此,对于您的 UITableView,您分配一个对象作为数据源和委托(delegate)。通常,但并非总是如此,人们会将包含的 ViewController 作为数据源和委托(delegate)。
override func viewDidLoad() {
tableView.dataSource = self
tableView.delegate = self
...
}
但是,您首先必须使 ViewController 符合这些协议(protocol)。
public class CustomViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
命令单击两个一致性声明,您将能够看到必须添加到 View Controller 以符合的方法。它们的作用非常明显,您可能可以从那里弄明白。
但具体来说,您需要添加 numberOfRows、numberOfSections 和此方法,我认为这就是您要问的问题。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// dequeue a cell for reuse
// type cast the cell to your UITableViewCell subclass
// set the device name and device status labels like so..
cell.deviceName = deviceController.devices[indexPath.row].name
cell.deviceStatus = deviceController.devices[indexPath.row].status
return cell
}
从那里开始,tableView 将在布局 subview 时自动请求数据。如果您的数据并非立即可用,您可以在可用时调用 tableView.reloadData()。
关于ios - 如何使用 Swift 3、ReativeKit 和 Bond 绑定(bind)自定义对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41580830/