[英]Passing data from UITableViewDataSource to UIViewController using protocol and delegate in Swift
I'm trying to pass data from a UITableViewDataSource to a UIViewController when a table row is selected. 当尝试选择表行时,我试图将数据从UITableViewDataSource传递到UIViewController。 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 View Controller-缩写
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. 问题是您只声明了busDataDelegate
对象,没有busDataDelegate
分配任何内容或未分配任何内容。
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. 但是从来没有为该对象分配任何东西或分配它,这就是问题所在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.