web-dev-qa-db-fra.com

Se conformer au protocole dans ViewController, dans Swift

Essayer de se conformer à UITableViewDataSource et UITableViewDelegate dans une sous-classe Swift UIViewController.

class GameList: UIViewController {

    var aTableView:UITableView = UITableView()

    override func viewDidLoad() {
        super.viewDidLoad()
        aTableView.delegate = self
        aTableView.dataSource = self
        self.view.addSubview(aTableView)
        //errors on both lines for not conforming
    }

}

Les documents indiquent que vous devez vous conformer sur la ligne class après le : mais c'est généralement là où va la superclasse. Un autre : ne fonctionne pas. L'utilisation d'une liste séparée par des virgules après la superclasse ne fonctionne pas non plus

ÉDITER:

Réponse trouvée ci-dessous. class GameList: UIViewController, UITableViewDataSource, UITableViewDelegate {

Je dois également adopter toutes les méthodes requises de chaque protocole, ce que je ne faisais pas initialement.

23
Justin

Vous utilisez une virgule:

class GameList: UIViewController, UITableViewDelegate, UITableViewDataSource {
    // ...
}

Mais sachez que la super classe doit être le premier élément de la liste séparée par des virgules.

Si vous n'adoptez pas toutes les méthodes requises du protocole, il y aura une erreur de compilation. Vous devez obtenir toutes les méthodes requises!

32
Firo

Comme les versions XCode6-Beta7,

J'ai remarqué que la méthode de protocole de UITableViewDataSource a changé un peu et sonnait la même erreur de protocole conforme qui fonctionnait bien en bêta6.

Ce sont les méthodes requises à implémenter selon le protocole UITableViewDataSource :

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // insert code}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // insert code
}

Vous voudrez peut-être revérifier la différence ou réimplémenter la méthode déléguée que vous pensiez implémenter.

13
Berby Huang

Vous devez implémenter deux méthodes require ici:

func tableView(tableView:UITableView!, numberOfRowsInSection section:Int) -> Int {
    return 10
}

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

    cell.text = "Row #\(indexPath.row)"
    cell.detailTextLabel.text = "Subtitle #\(indexPath.row)"

    return cell
}
7
Kiet Nguyen

En outre, il est important de copier toutes les fonctions non facultatives de la classe Delegate. Cmd + Cliquez sur UITableViewDatasource et copiez ces deux définitions telles quelles.

Pour moi en version beta7, UITableViewDatasource a

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int

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

Ma mise en œuvre:

var items = ["Apple", "Pear", "Banana"]

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Default")
    cell.textLabel?.text = items[indexPath.row]
    cell.detailTextLabel?.text = "Test"
    return cell

}
3
skipy

Utilisez ces méthodes: Il y a un changement dans les méthodes de source de données -

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int

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


protocol UITableViewDataSource : NSObjectProtocol {

    ****func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int

    // Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
    // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell****

    optional func numberOfSectionsInTableView(tableView: UITableView) -> Int // Default is 1 if not implemented

    optional func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? // fixed font style. use custom view (UILabel) if you want something different
    optional func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String?

    // Editing

    // Individual rows can opt out of having the -editing property set for them. If not implemented, all rows are assumed to be editable.
    optional func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool

    // Moving/reordering

    // Allows the reorder accessory view to optionally be shown for a particular row. By default, the reorder control will be shown only if the datasource implements -tableView:moveRowAtIndexPath:toIndexPath:
    optional func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool

    // Index

    optional func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! // return list of section titles to display in section index view (e.g. "ABCD...Z#")
    optional func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int // tell table which section corresponds to section title/index (e.g. "B",1))

    // Data manipulation - insert and delete support

    // After a row has the minus or plus button invoked (based on the UITableViewCellEditingStyle for the cell), the dataSource must commit the change
    // Not called for edit actions using UITableViewRowAction - the action's handler will be invoked instead
    optional func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)

    // Data manipulation - reorder / moving support

    optional func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath)
}

Votre code fonctionnera !!

1
Rohit Ragmahale

Cette question est déjà répondue, mais je veux juste rendre les choses un peu plus Swifty.

Au lieu d'écrire des protocoles dans UITableViewDelegate, UITableViewDataSource vous pouvez les diviser en utilisant extensions cela vous aidera à organiser le code. L'ajout de conformité au protocole est décrit dans ce page

pour la question ci-dessus, cela peut être confirmé au protocole en utilisant l'extension:

class GameList: UIViewController {
  var aTableView:UITableView = UITableView()
    override func viewDidLoad() {
        super.viewDidLoad()
        aTableView.delegate = self
        aTableView.dataSource = self
        self.view.addSubview(aTableView)
    }
}
extension GameList: UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return list.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath)
        return cell
    }
}
extension GameList: UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("Row Clicked at \(indexPath.row)")
    }
}
1
Sahil Manchanda