2017-01-11 35 views
0

背景 我有一個可以接收實時數據流的IOS應用程序。我已經實現了自定義值對象來存儲/捕獲實時流中的這些數據。我現在需要將我的自定義數據對象綁定到UI(主要使用調用這些自定義對象值的表格和自定義單元格)。如何使用Swift 3,ReativeKit和Bond綁定一組自定義對象

問題 如何在Swift 3中使用Bond,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! 
} 

回答

0

可以使用委託模式,這是已經建立了許多的UIKit元素,包括的UITableView。

一個UITableView有兩個屬性,可以是符合兩種協議的任何物體,特別是

var dataSource: UITableViewDataSource? 
var delegate: UITableViewDelegate? 

因此,對於你的UITableView,您分配一個對象來充當數據源和委託。通常(但並非總是),可以使包含ViewController的數據源和委託都成爲可能。

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()。

+0

我已經有代碼編碼/實現非常類似於您建議的代碼。當我調用一個REST API並填充我的自定義對象數組(將其分配給一個表格單元格)時,此技術運行良好。問題是我現在有一個實時饋送流到我的應用程序,反過來我更新我的數組內的自定義對象,但我的tableview單元不知道什麼時候自定義對象的值正在改變,這就是爲什麼我' m查看將數據值綁定到UI組件的ReactiveKit/Bond /其他框架 – Cameron