在Swift中以编程方式创建一个UITableViewController

Nil*_*ne- 7 uitableview programmatically-created swift ios8

正如标题所说,我试图以编程方式设置UITableViewController.经过几个小时的尝试,我希望有人可以帮助我.而且,是的,我已经检查了有关此事的其他帖子:

import UIKit

class MainViewController: UITableViewController {

    init(style: UITableViewStyle) {
        super.init(style: style)
        // Custom initialization
    }

    override func viewDidLoad() {
        super.viewDidLoad()


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // #pragma mark - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView?) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
        return 5
    }


    override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
        var cell = tableView?.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell

        if !cell {
            cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "Cell")
        }
        cell!.textLabel.text = "test"
        return cell
    }

}
Run Code Online (Sandbox Code Playgroud)

并且appDelegate看起来像这样:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

        let mainViewController: UITableViewController = MainViewController(style: UITableViewStyle.Plain)
        let navigationController: UINavigationController = UINavigationController()
        navigationController.pushViewController(mainViewController, animated: false)

        self.window!.rootViewController = navigationController
        self.window!.backgroundColor = UIColor.whiteColor()
        self.window!.makeKeyAndVisible()
        return true
    }
Run Code Online (Sandbox Code Playgroud)

该程序运行,但一旦它运行,我收到以下错误:

fatal error: use of unimplemented initializer 'init(nibName:bundle:)' for class 'HelloWorld.MainViewController'
Run Code Online (Sandbox Code Playgroud)

我然后更改MainViewController(style: UITableViewStyle.Plain)MainViewController(nibName: nil, bundle: nil)但然后我得到以下语法错误:Extra argument 'bundle' in call

任何帮助将非常感激

Ben*_*ieb 3

我使用 UITableViewController 的子类,没有任何问题,使用 (nibName:bundle:) 形式,但我已经在我的子类中覆盖了它。我尝试用标准 UITableViewController 替换我的子类,它仍然工作正常。您是否可能重写子类中的 init(...) 方法?

  • 当您添加指定的初始值设定项时,Swift 会使派生类的客户端无法访问继承的初始值设定项。它看起来类似于 C++ 中的私有继承,其中继承的方法/数据被隐式移动到“私有”类部分。原因很简单:如果有自定义初始值设定项,那么您的类可能需要此初始值设定项来构造“不变”类。但有一个错误:如果您创建从 UITableViewController 派生的类并添加调用 super.init(style:) 的自定义初始值设定项,它将失败,并显示_使用未实现的初始值设定项 'init(nibName:bundle:)'_ (6认同)