ios - TableView 项目应该加载另一个 TableView

标签 ios swift xcode

对于大学,我必须编写一个小应用程序,其想法是创建一个小公式集合。这个概念是有一个类别列表,选择类别后您会收到一个公式列表。选择所需的公式后,您将看到公式计算器的 View 。

我正在努力获得第一个UITableViewController加载另一个UITableViewController 。我编辑了 Storyboard,所以在我看来它应该有效,但事实并非如此。它给我的错误也根本没有帮助:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

我该如何实现这一目标?

我的MasterViewController :

import UIKit

class MasterViewController: UITableViewController {

    var detailViewController: FormulaListViewController? = nil
    var categoryList = TestData.sharedInstance.categoryList


    override func viewDidLoad() {
        super.viewDidLoad()
        if let split = splitViewController {
            let controllers = split.viewControllers
            detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? FormulaListViewController
        }
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.tableView .reloadData()
        for category in categoryList {
            print(category)
        }

    }
    override func viewWillAppear(_ animated: Bool) {
        clearsSelectionOnViewWillAppear = splitViewController!.isCollapsed
        super.viewWillAppear(animated)
    }



    // MARK: - Segues

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showForumlaList" {
            if let indexPath = tableView.indexPathForSelectedRow {
                let object = categoryList[indexPath.row]
                let controller = (segue.destination as! UINavigationController).topViewController as! FormulaListViewController
                controller.category = object
                controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
                controller.navigationItem.leftItemsSupplementBackButton = true
            }
        }
    }

    // MARK: - Table View

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return categoryList.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        let object = categoryList[indexPath.row]
        cell.textLabel!.text = object.description
        return cell
    }

    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            categoryList.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
        }
    }
}

FormulaListViewController :

import UIKit

class FormulaListViewController: UITableViewController {

    @IBOutlet weak var categoryLabel: UILabel!

    var category: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        categoryLabel.text = category
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        categoryLabel.text = category
    }

    var detailItem: String? {
        didSet {
            // Update the view.
        }
    }
}

错误来自AppDelegate : 具体来说这一行:navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        let splitViewController = window!.rootViewController as! UISplitViewController
        let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
        navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
        splitViewController.delegate = self
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    // MARK: - Split view

    func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool {
        guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
        guard let topAsDetailController = secondaryAsNavController.topViewController as? FormulaListViewController else { return false }
        if topAsDetailController.detailItem == nil {
            // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
            return true
        }
        return false
    }

}

项目模型:

主屏幕:https://snag.gy/WTECxZ.jpg

用户选择“Wasserbau”,他将获得公式列表:https://snag.gy/2mWoEB.jpg

用户然后选择“Fliessformel”:https://snag.gy/D3h5L2.jpg

由于我无法真正分享我的 Storyboard,我还上传了整个项目:https://cloud.aintevenmad.ch/index.php/s/QakGibkAXfmKDxp

感谢您的帮助!

最佳答案

我建议您更改项目的结构。在 MasterViewController 中添加 UITableView didSelectRowAtIndexPath 方法。

在此didSelectRowAtIndexPath中,编写导航代码。

关于ios - TableView 项目应该加载另一个 TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53460849/

相关文章:

ios - 自定义推送警报声音无法更新?

iphone - IOS的密码认证如何设计和实现?

android - 在 Cordova 和 Ionic 中检测屏幕关闭/打开

ios - UIPageViewController 旋转怪异

ios - 数据从 watch 发送到手机后未调用 Swift 3 XML 解析委托(delegate)

ios - AudioKit:将新的 AKSequencer 与任何种类的回调乐器结合使用

ios - Cocos2d-x AdMob iOS 集成错误

ios - 按下主页按钮时如何关闭 UIAlertView?

ios - 在 ViewController 中连接 TableView - self.tableView.reloadData() 在 Swift 中不起作用

ios - iOS两个圆形的矩形