Подтвердить что ты не робот

Программно UITableView с использованием быстрой

Я пытаюсь создать простой tableView программно с помощью swift, поэтому я написал этот код на "AppDelegate.swift":

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

    var tvc :TableViewController = TableViewController(style: UITableViewStyle.Plain)
    self.window!.rootViewController = tvc

    self.window!.backgroundColor = UIColor.whiteColor()
    self.window!.makeKeyAndVisible()
    return true
    }

В основном я добавил создание TableViewController и добавил его в окно. И это код TableViewController:

class TableViewController: UITableViewController {

init(style: UITableViewStyle) {
    super.init(style: style)
 }

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 10
}


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

    cell.textLabel.text = "Hello World"

    return cell
}

}

Итак, когда я пытаюсь запустить код, я получаю это сообщение:

Xcode6Projects/TableSwift/TableSwift/TableViewController.swift: 12: 12: фатальная ошибка: использование нереализованного инициализатора 'init (nibName: bundle:)' для класса 'TableSwift.TableViewController'

Ошибка возникает, когда компилятор выполняет

super.init(стиль: стиль)

Любые мысли?

4b9b3361

Ответ 1

В Xcode 6 Beta 4

Удаление

init(style: UITableViewStyle) {
    super.init(style: style)
}

сделает трюк. Это вызвано различными поведениями инициализатора между Obj-C и Swift. Вы создали назначенный инициализатор. Если вы удалите его, все инициализаторы будут унаследованы.

Коренная причина, вероятно, находится в -[UITableViewController initWithStyle:], которая вызывает

[self initWithNibName:bundle:]

Я действительно думаю, что это может быть ошибкой в ​​том, как классы Obj-C преобразуются в классы Swift.

Ответ 2

Вместо

init(style: UITableViewStyle) {
    super.init(style: style)
}

вы можете найти это удобным:

convenience init() {
    self.init(style: .Plain)
    title = "Plain Table"
}

Затем вы можете просто вызвать TableViewController() для инициализации.

Ответ 3

Это так же просто, как написать функцию

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
    let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell")

    cell.text = self.Myarray[indexPath.row]
    cell.textLabel.textColor = UIColor.greenColor()

    cell.detailTextLabel.text = "DummyData #\(indexPath.row)"
    cell.detailTextLabel.textColor = UIColor.redColor()
    cell.imageView.image = UIImage(named:"123.png")
    return cell
}

Ответ 4

Функция соты:

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{

    var cell = tableView.dequeueReusableCellWithIdentifier(kLCellIdentifier) as UITableViewCell!
    if !cell {
        cell = UITableViewCell(style:.Default, reuseIdentifier: kLCellIdentifier)
    }
    cell.backgroundColor = UIColor.clearColor()
    cell.textLabel.text = arrData[indexPath.row]
    cell.image = UIImage(named: "\(arrImage[indexPath.row])")   
    cell.accessoryType  = UITableViewCellAccessoryType.DetailDisclosureButton
    cell.selectionStyle = UITableViewCellSelectionStyle.None
    return cell
}