私のテーブルビューには、上記のプロトコルに準拠するセルしか含まれていないことを確認したいと思います。私は特定の問題を説明するために実装を単純化しました。定義されたプロトコルに準拠するUITableViewCellsをデキューする方法
protocol ACommonLookAndFeel {
func configureMyLookAndFeel()
}
CellA: UITableViewCell, ACommonLookAndFeel
CellB: UITableViewCell, ACommonLookAndFeel
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell
if indexPath.row == 0 {
cell = tableView.dequeueReusableCellWithIdentifier("CellA", forIndexPath: indexPath) as! CellA
if let myCell = cell as? CellA {
myCell.configureMyLookAndFeel() // we need to call this for each cell
}
} else if indexPath.row == 1 {
cell = tableView.dequeueReusableCellWithIdentifier("CellB", forIndexPath: indexPath) as! CellB
if let myCell = cell as? CellB {
myCell.configureMyLookAndFeel() // we need to call this for each cell
}
}
return cell
}
上記のコードは、コードが繰り返されていることを除いて働いていると私はconfigureMyLookAndFeel()メソッドにアクセスするたびにキャストを行う必要があります。私はすべての細胞は一見のために構成して感じることにしたいように、私が代わりに以下のコードを試してみましたが、コンパイルエラー
エラーを打つ:型を返すためにタイプのリターン式「プロトコル」を変換できません「のUITableViewCell」
をfunc tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: protocol <ACommonLookAndFeel>
if indexPath.row == 0 {
cell = tableView.dequeueReusableCellWithIdentifier("CellA", forIndexPath: indexPath) as! CellA
} else if indexPath.row == 1 {
cell = tableView.dequeueReusableCellWithIdentifier("CellB", forIndexPath: indexPath) as! CellB
}
cell.configureMyLookAndFeel() // works
return cell // Compiler Error !
}
このコンパイラエラーを修正する方法はありますか?
理想的には私は内陣またはCELLBにdequeueCellへの呼び出しや鋳造の繰り返しを避けるためにのように持っていません。私はcellReuseIdentifierに基づいてそれをキャストする必要があるセルを知っています。これは私のセルクラス名と同じです。方法はありますか?
ありがとう!
私はまた、VARセルを試してみました。私はまだ同じコンパイラエラーを取得します。私のプロトコルの唯一の機能は、tableviewのセルの背景色を設定し、それを180度回転させるための変換を行うconfigureMyLookAndFeel()です。 –
あなたが得たエラーを誤解しました。私は私の答えを編集して、それをもう一度見てください。 –