2017-07-17 6 views
-2

のセルを作成して返します:cellForRowAt - 私はスウィフトへの根本的な何かが欠けていると思うが、私はしようとしている何をやって人々の他の例を見つけることができませんswitch文の中から

背景

私は異なる識別、異なる機能(ラベル、画像など)と異なるクラスを持つ2つのプロトタイプのセルを持つUITableViewを持っています。

テーブルデータを保持する配列の内容に応じて、cellForRowAt関数が異なるタイプとセルのクラスを返すようにします。この配列には構造体インスタンスが設定されています。その特性の1つは、データを表すセルのタイプを識別します。

コードは、問題はこれが動作しないです。これは、そのままコピー/貼り付けではありませんが、原理は同じ

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     switch dataArray[indexPath.item].typeOfData { 
     case "Type1": 
      let cell = tableView.dequeueReusableCell(withIdentifier: "type1ReuseIdentifier", for: indexPath) as! type1Cell 
      //Set up the cell contents 
      return cell 
     case "Type2": 
      let cell = tableView.dequeueReusableCell(withIdentifier: "type2ReuseIdentifier", for: indexPath) as! type2Cell 
      //Set up the cell contents 
      return cell 
     default 
      let cell = tableView.dequeueReusableCell(withIdentifier: "separatorIdentifier", for: indexPath) as! separatorCell 
      //Set up the cell contents 
      return cell 
    } 
} 

ある

を試み、スウィフトは私が宣言したいとswitchステートメントの外側にセルを返しますが、セルタイプの宣言は作成するデータのタイプに依存します(カスタムセルのコンポーネントにアクセスするためには!typexCellが必要です)。

何が間違っていますか/間違っていますか?

+0

を返すために別の方法を使用して、あなたはdefaultをケースに書かれたことがありますか? – iPeter

+0

[返品がありませんUITableViewCell](https://stackoverflow.com/questions/30189505/missing-return-uitableviewcell)を比較してください。 –

+0

申し訳ありませんが、デフォルトのステートメントもあり、セパレータタイプのセルを返します – KnowledgeQuest

答えて

1

はちょうどこのように実行します。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    let typeSection = CellType(rawValue: indexPath.row)! 

    switch typeSection { 
    case .CenterTitleCell: 
     return getCenterTitleCell(tableView, indexPath) 
    case .CenterDescriptionCell: 
     return getCenterDescriptionCell(tableView, indexPath) 
    case .CenterImageCell: 
     return getImageCell(tableView, indexPath) 
    case .FooterTitleCell: 
     return getFooterViewCell(tableView, indexPath) 
    } 
} 

を、セルタイプ

func getCenterTitleCell (_ tableView: UITableView, _ indexPath:IndexPath) -> CenterTitleTableViewCell { 
    let cell:CenterTitleTableViewCell = tableView.dequeueReusableCell(withIdentifier: String(describing: CenterTitleTableViewCell.self), 
                        for: indexPath) as! CenterTitleTableViewCell 
    cell.selectionStyle = .none 
    return cell 
} 
+0

これは、4行しかなく、各行が独自のセルタイプを取得すると仮定します。一般に、これはほとんどのテーブルがどのようにセットアップされるかではありません。 – rmaddy

+0

これは簡単な例です。この場合、静的な画面なので、セル型を提供する列挙型があります。彼が望むコードにこの例を適応させるべきです。 – ppinho

関連する問題