2016-12-30 8 views
2

ここに私が直面している問題があります。 私が何をしたいのかを見文字列を使用してクラス参照を作成する方法

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    if indexPath.row == 0 { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "ExpenseTableViewCell_Title") as! ExpenseTableViewCell_Title 
     return cell 
    } else { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "ExpenseTableViewCell_SaveCanel") as! ExpenseTableViewCell_SaveCanel 
     return cell 
    } 
} 

を取ることは、細胞型としてセル識別子の文字列を使用して、ある。(すなわち。ExpenseTableViewCell_Title、ExpenseTableViewCell_SaveCanel)。

私はセル識別子配列を持っています。

var TableCell:[ExpenseCellType] = [.ExpenseTableViewCell_Title, .ExpenseTableViewCell_SaveCanel] 

今は2種類のセルしかありません。しかし、この数字は高くなるでしょう。 if/else条件やスイッチケースを使いたくないです。

ありがとうございます。

+0

スウィフトはstrですictをタイプチェックします。だからあなたはこれを避けることはできません。 – Lumialxk

答えて

2

機能NSClassfromStringを使用できますが、Stringからクラスを取得するには名前空間が必要です。

私はここでそれを使用する例を作成しました。 例:

func getClassFromString(_ className: String) -> AnyClass! { 


    let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String; 
    let cls: AnyClass = NSClassFromString("\(namespace).\(className)")!; 

    return cls; 
} 


    class customcell: UITableViewCell { 

     } 

    let requiredclass = getClassFromString("customcell") as! UITableViewCell.Type 
    let cellInstance = requiredclass.init() 
+0

お返事ありがとうございますが、 "stringClassFromString"という名前の関数が見つかりました。私は "NSClassFromString"を試みましたが。それはどちらもうまくいきませんでした。 – rv7284

3

は拡張子を持つ、それを短くすることができます:

extension UITableView { 
    func dequeueReusable<T>(type: T.Type, index: IndexPath) -> T { 
     return self.dequeueReusableCell(withIdentifier: String(describing: T.self), for: index) as! T 
    } 
} 

ExpenseTableViewCell_Title型セルを返しますが、このようにそれを使用します。

let cell = tableView.dequeueReusable(type: ExpenseTableViewCell_Title.self, index: indexPath) 

だけのような配列で、あなたのクラスを保存します[ExpenseTableViewCell_Title.self, ExpenseTableViewCell_SaveCanel.self]この関数に渡す

+0

ありがとう、私はこれを試してみます。 – rv7284

関連する問題