背景I有一个IOS应用程序,可以接收实时数据流.我已经实现了自定义值对象来存储/捕获活动流中的数据。现在,我需要将我的自定义数据对象绑定到UI (主要使用表视图和自定义单元格来调用这些自定义对象值)。
问题如何使用Swift 3中的邦德、ReactiveKit或其他框架将自定义对象值数组绑定到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!
}发布于 2017-01-11 01:11:43
您可以使用委托模式,它已经为许多UIKit元素(包括UITableView )设置了。
UITableView有两个属性,可以是符合两个协议的任何对象,特别是
var dataSource: UITableViewDataSource?
var delegate: UITableViewDelegate?因此,对于您的UITableView,您分配一个对象作为dataSource和委托。通常,但并不总是,一个人会使包含的ViewController同时成为dataSource和委托。
override func viewDidLoad() {
tableView.dataSource = self
tableView.delegate = self
...
}但是,您首先必须使ViewController符合这些协议。
public class CustomViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {命令单击这两个一致性声明,您就可以看到必须添加到视图控制器中的方法才能符合。他们做什么是很明显的,你可能会从那里找出答案。
但具体而言,您需要添加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将在子视图布局时自动请求数据。如果您的数据不是即时可用的,则可以在数据可用时调用tableView.reloadData()。
https://stackoverflow.com/questions/41580830
复制相似问题