【发布时间】: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