2015-12-17 10 views
6

jest następująca realizacja cellForRowAtIndexPath technicznie poprawny sposób najlepszych praktyk z uwzględnieniem rozpakowaniu optionalsPrawidłowa realizacja cellForRowAtIndexPath w Swift 2.0

class MyTableViewController: UITableViewController { 
     var cell : UITableViewCell? 
     // other methods here 
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     cell = tableView.dequeueReusableCellWithIdentifier("ItemCell")! as UITableViewCell 
     let myItem = items[indexPath.row] 

     cell!.textLabel?.text = myItem.name 
     cell!.detailTextLabel?.text = myItem.addedByUser 

     return cell! 
     } 

    } 
+3

Nie ma powodu, aby mieć opcjonalną zmienną komórki poza metodą, po prostu wprowadź nie-opcjonalną zmienną lokalną w metodzie – dan

+1

Wskazówka: Utwórz nową aplikację Xcode za pomocą szablonu "Master-Detail Application", a otrzymasz próbkę kod za darmo. –

Odpowiedz

7

W Swift 2 dequeueReusableCellWithIdentifier jest zadeklarowana jako

func dequeueReusableCellWithIdentifier(_ identifier: String, 
         forIndexPath indexPath: NSIndexPath) -> UITableViewCell 

i cellForRowAtIndexPath jest zadeklarowany jako

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

Widzisz, Brak opcji!

Kod może zostać zmniejszona do

class MyTableViewController: UITableViewController { 

    // other methods here 
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: indexPath) 
    let myItem = items[indexPath.row] 

    cell.textLabel?.text = myItem.name 
    cell.detailTextLabel?.text = myItem.addedByUser 

    return cell 
    } 
} 

W przypadku niestandardowych komórki widoku tabeli komórka może być zmuszony do lanego typu niestandardowego.

let cell = tableView.dequeueReusableCellWithIdentifier("ItemCell", forIndexPath: indexPath) as! CustomCell 

Zawsze dobrze jest kliknąć symbol prawym przyciskiem myszy lub skorzystać z Szybkiej pomocy, aby sprawdzić dokładny podpis.

+0

Jeśli spróbuję pozwolić komórce = tableView.dequeueReusableCellWithIdentifier ("ItemCell") jako UITableViewCell bez rozpakowywania, kompilator zasugeruje, że powinienem rozpakować używając !, tak jak w allow cell = tableView.dequeueReusableCellWithIdentifier ("ItemCell")! jako UITableViewCell Poza tym twój kod działa! – Das

+0

Nie trzeba niczego odwracać, ponieważ wszystkie istotne parametry nie są opcjami. – vadian

+1

Powiedziałeś, że używasz drugiej metody, która pobiera parametr ścieżki indeksu, ale twój przykład nadal używa niewłaściwej metody – dan