【问题标题】:Passing data from UITableViewDataSource to UIViewController using protocol and delegate in Swift在 Swift 中使用协议和委托将数据从 UITableViewDataSource 传递到 UIViewController
【发布时间】:2015-03-01 09:32:37
【问题描述】:

I'm trying to pass data from a UITableViewDataSource to a UIViewController when a table row is selected.我想我已经很接近了。

协议

protocol BusDataDelegate {
    func didSelectRow(row: NSIndexPath, data: Route)
}

数据源

class BusUITableView: NSObject, UITableViewDelegate, UITableViewDataSource {

    var busDataDelegate: BusDataDelegate?

    var routeService: RouteService = RouteService()

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        var busRoutes: [Route] = routeService.retrieve()
        return busRoutes.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var cell:BusUITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as BusUITableViewCell

        var busRoutes: [Route] = routeService.retrieve()

        cell.routeName.text = busRoutes[indexPath.row].name
        cell.routeNumber.text = busRoutes[indexPath.row].id
        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        var busRoutes: [Route] = routeService.retrieve()

        busDataDelegate?.didSelectRow(indexPath, data: busRoutes[indexPath.row])
        println("You selected cell #\(indexPath.row)!")

    }

}

视图控制器 - 缩写

class ViewController: UIViewController, MKMapViewDelegate, BusDataDelegate {

    func didSelectRow(row: NSIndexPath, data: Route) {
        println("Row: \(row) Data: \(data)")
    }

}

【问题讨论】:

  • 你能解释一下问题是什么吗?你只是放了代码,没有解释问题。
  • 点击表格视图单元格时,我想将该数据传递给视图控制器。至于现在我只想调用 didSelectRow 函数,它应该能够访问被选中行的数据。

标签: ios uitableview swift delegates protocols


【解决方案1】:

问题是你只声明了 busDataDelegate 对象,没有分配任何东西给它或没有分配它。

你是这样声明的:

var busDataDelegate: BusDataDelegate?

并像这样使用它:

busDataDelegate?.didSelectRow(indexPath, data: busRoutes[indexPath.row])

但从来没有为那个对象分配任何东西或分配它,这就是问题所在。

【讨论】:

  • 您能告诉我如何进行必要的更改吗?
  • @RobertHirsch:您从哪里显示ViewControllerBusUITableView
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-08
  • 2023-04-07
  • 2013-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多