【发布时间】:2017-04-29 16:39:22
【问题描述】:
我正在测试 Apple, Inc. 的一个 Swift 示例项目。它名为 Table Search with UISearchController。我试过了。它运行。所以我在 Swift 3 中从头开始制作了一个示例。无论如何,以下是我所拥有的。
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Product is a data model class.
let products = [
Product(hardwareType: Product.deviceTypeTitle, title: Product.Hardware.iPhone.rawValue, yearIntroduced: 2007, introPrice: 599.00),
Product(hardwareType: Product.deviceTypeTitle, title: Product.Hardware.iPod.rawValue, yearIntroduced: 2001, introPrice: 399.00), ...
]
let navController = window!.rootViewController as! UINavigationController
let tableViewController = navController.viewControllers.first as! MainTableViewController
tableViewController.products = products
return true
}
}
// MainTableViewController, BaseTableViewController are subclasses of UITableViewController
class MainTableViewController: BaseTableViewController {
var products = [Product]()
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return products.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(BaseTableViewController.tableViewCellIdentifier, forIndexPath: indexPath)
let product = products[indexPath.row]
configureCell(cell, forProduct: product)
return cell
}
}
正如AppDelegate 所暗示的,这个表格视图控制器有一个导航栏。并且 AppDelegate 将成功地将数据传递给表视图控制器。如果没有怎么办?所以我有以下内容。
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let products = [ ... ]
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let tableViewController = storyboard.instantiateViewController(withIdentifier: "tableController") as! MainTableViewController
tableViewController.data = dataSet
return true
}
}
而tableViewController 永远不会及时从AppDelegate 获取数据。我知道如何更改它,以便表视图控制器本身将从 AppDelegate 获取数据。但是如何让 AppDelegate 将数据推送到表视图控制器?我是否必须为此过程使用协议?
谢谢。
【问题讨论】:
标签: ios swift tableview appdelegate