我正在测试一个由苹果公司的Swift示例项目,它叫做Table Search with UISearchController
。我试过了。它运行。所以我在Swift 3中从头开始做一个例子。无论如何,下面是我的。从AppDelegate传递数据到TableViewController没有NavigationBar
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将数据推送到表视图控制器?我必须使用该过程的协议吗?
谢谢。
谢谢。但它实际上是tableViewController.data = dataSet。你有什么想法如果MainTableViewController不是rootViewController? –
@ElTomato检查编辑后的答案是否符合要求。 –
好的。非常感谢。 –