I'm trying to pass data from a UITableViewDataSource to a UIViewController when a table row is selected. I think I'm pretty close.
Protocol
protocol BusDataDelegate {
func didSelectRow(row: NSIndexPath, data: Route)
}
Data Source
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)!")
}
}
View Controller - abbreviated
class ViewController: UIViewController, MKMapViewDelegate, BusDataDelegate {
func didSelectRow(row: NSIndexPath, data: Route) {
println("Row: \(row) Data: \(data)")
}
}
The issue is you only declared the busDataDelegate
object, not assigned anything to it or not allocated it.
You are declaring it like:
var busDataDelegate: BusDataDelegate?
And using it like:
busDataDelegate?.didSelectRow(indexPath, data: busRoutes[indexPath.row])
But never assigned anything to that object or allocated it, that's the problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.