簡體   English   中英

如何使用Swift 3,ReativeKit和Bond綁定自定義對象數組

[英]How To Bind An Array Of Custom Objects Using Swift 3, ReativeKit, and Bond

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

問題如何使用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!
}

您可以使用委托模式,該模式已經為許多UIKit元素設置,包括UITableView。

UITableView有兩個屬性,可以是符合兩個協議的任何對象,具體而言

var dataSource: UITableViewDataSource?
var delegate: UITableViewDelegate?

因此,對於您的UITableView,您可以指定一個對象作為dataSource和delegate。 通常,但並非總是如此,將使包含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()。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM