Le Swift : Développement d'une application iOS | Zoom sur des composants #1 | Partie 3

Mathieu ?

IT Officer @STATION F
Premium
Inscription
19 Novembre 2016
Messages
1 247
Réactions
1 460
Points
12 310
Swift.png


Le Swift : Développement d'une application iOS | Les composants controller | Partie 1
Le Swift : Développement d'une application iOS | Les composants les plus utilisés | Partie 2


Zoom sur TableView & TableViewController

La TableView et la TableViewController sont deux éléments similaire comme expliquer dans les parties précédentes. Je vais donc expliquer les différentes fonction en prenant la TableViewController et je passerais rapidement sur l’intégration de la TableView sur une ViewController.

Lorsque vous ajouter un Controller vous devez aussi créer le fichier CocoaTouch assigner a celui-ci (Tout seras expliquer dans une prochaine partie).

Le fichier d'une table view controller contient ce code par défaut:
Swift:
//
//  TUTOTableViewController.swift
//  tutoRG
//
//  Created by Marent on 28/12/2016.
//  Copyright © 2016 Marent. All rights reserved.
//

import UIKit

class TUTOTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }

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

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 0
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 0
    }


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

        // Configure the cell...

        return cell
    }


    /*
    // Override to support conditional editing of the table view.
    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 to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            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
        }
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

Nous pouvons y retrouver 2 fonction présente sur tout les controller qui sont viewDidLoad et didReceiveMemoryWarning. La première fonction permet de faire une ou plusieurs action au moment du chargement de la View et la deuxième qui n'est jamais utiliser enfin autrement dit elle n'est jamais appeler par le programme pour être exécuté a moins que la mémoire de l'appareil soit bas.

Il y a trois fonctions importante pour avoir une Table View Controller fonctionelle qui sont : numberOfSections, numberOfRowsInsection, cellForRowAt.

Je vais vous présenter la table view avec le minimum c'est a dire 1 section et la cellule de base (Titre seulement).
Commençons tout de suite par mettre le nombre de section a 1 ce qui nous donne:
Swift:
  override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

Ensuite nous allons renseigner le nombre de cellule (lignes) que nous voulons :
Swift:
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 4  //Mettez le nombre que vous shouaitez !
    }

Et enfin nous allons configurer la fonction qui va permettre de remplir les lignes, dans un premier temps elles auront tous le même contenue :
Swift:
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellname")! as UITableViewCell

        // Configure the cell...
       cell.textlabel?.text = "Swift Tuto"
        return cell
    }

Nous allons ensuite aller sur Main.storyboard, puis sélectionner la première cellule. Dans les paramètres a droite modifier sont identifier par celui renseigner dans le code qui est cellname. Vous pouvez maintenant appuyer sur le bouton pour lancer votre application. Vous devriez obtenir ceci :

upload_2016-12-28_17-41-34.png


Voila vous avez maintenant les bases de la Table View & Table View Controller

Intégration d'une Table View a une View Controller

Pour intégrer une Table View rien de plus simple, glisser l’élément table View sur votre View puis relier les Outlets dataSource et delegate a la view controller en clickant dessus comme ceci :

upload_2016-12-28_17-52-47.png
upload_2016-12-28_17-53-2.png


Une fois cela fais rendez vous dans le fichier swift de votre view controller
Le code présent de base:
Swift:
//
//  ViewController.swift
//  tutoRG
//
//  Created by Marent on 28/12/2016.
//  Copyright © 2016 Marent. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

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

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


}

Nous allons devoir étendre notre classe pour la rendre compatible avec notre Table View pour cela ajouter a la place de ceci :
Swift:
class ViewController: UIViewController {
Le code suivant:
Swift:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

Voila maintenant votre classe est compatible avec la tableview il ne vous reste plus qu'a y ajouter les 2 fonction qui permette le bon fonctionnement de la tableview :
Swift:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellname")! as UITableViewCell
   
        cell.textLabel?.text = "Swift Tuto"
        return cell
    }

Conclusion la TableView n’est pas un éléments compliquer a coder il faut juste le coup de mains et ensuite de belle choses peuvent être faites. Nous verrons plus tard comment ajouter une action au swipe ou même comment déplacer des cellules ::):

Le Swift : Développement d'une application iOS | Zoom sur des composants #2 | Partie 4

 
Dernière édition:
Haut