2017-05-20 8 views
0

UITableViewでは2つの異なるUITableViewCellを使用する必要がありますが、これらの2つのセルは非常に類似しています。さんは今ここに、私のコードの例を本題にしてみましょう:プロトコルを使用してUITableViewで複数のUITableViewCellプロトタイプを作成するにはどうすればよいですか?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    if a { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "firstCell") as! FirstTableViewCell 
     cell.config(withData: self.data[indexPath.row]) 
     return cell 
    } else { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "secondCell") as! SecondTableViewCell 
     cell.config(withData: self.data[indexPath.row]) 
     return cell 
    } 
} 

私が欲しいものは、このようなものです:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: a.cellIdentifier) as! MyTableViewCellProtocol 
    cell.config(withData: self.data[indexPath.row]) 
    return cell 
} 

私は、これは持っている、親クラスを作成して行うことができることを知っていますその親クラスから継承されているFirstTableViewCellSecondTableViewCellですが、私はProtocolを使ってこれを達成したいと思います。

ありがとうございます。ここで

答えて

2

そんなにありがとうねえ...

class FirstTableViewCell: UITableViewCell, MyTableViewCellProtocol { 
    func config(withData: Any) { 

    } 
} 

class SecondTableViewCell: UITableViewCell, MyTableViewCellProtocol { 
    func config(withData: Any) { 

    } 
} 

protocol MyTableViewCellProtocol { 
    func config(withData:Any) 
} 

そして

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: a.cellIdentifier) as! MyTableViewCellProtocol 
    cell.config(withData: self.data[indexPath.row]) 
    return cell as! UITableViewCell 
} 
+0

を行きます! – Norak

関連する問題