我正在測試一個由蘋果公司的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檢查編輯後的答案是否符合要求。 –
好的。非常感謝。 –