2017-09-16 21 views
-2

配列内にUITableViewCellテキストを見つけようとしています。問題は関係なく、私がクリックてる何セルではありません、array.index(of:)は常に1array.index(of:)が正しく動作していません

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 
    if let text = cell.textLabel?.text { 
     let indexOfCellString = event.index(of: text) 
     print (indexOfCellString!) 
    } 

} 
//here is my attempt to set the cell text: 
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ 

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) 
    if eventIndex.indices.contains(indexPath.row) == true { 
    cell.textLabel?.text = event [indexPath.row] 
    } 

    return cell 
} 

イベントは私が検索し、セルのテキストを検索しようとしている配列で返します。 セルのテキストは常にイベントのインデックスにあります。私のテーブルビューはイベント配列から情報を読み込むためです。したがって、必ずしも1を返すべきではありません。 何が間違っていますか?

+3

詳細については、誰も助けてくれません。あなたは 'イベント 'が何であるかを説明していません。あなたは、 'text'に何が含まれているかについての詳細を提供していません。投稿したコードは無効です。 「自己」行とは何ですか? – rmaddy

+0

これは、cell.textlable.textが入っているイベントのインデックスを返します。 しかし、どのテーブル行をタップしても、常に1が返されます。テーブル行には別の文字列があります。 – Farbod

+0

あなたの試みはどこですかセルのラベルのテキストを設定しますか? – rmaddy

答えて

1

cellForRowAt以外のdequeueReusableCellを絶対に使用しないでください。データモデルからデータにアクセスするだけです。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    if eventIndex.indices.contains(indexPath.row) == true { 
     let text = event[indexPath.row] 
     if let indexOfCellString = event.index(of: text) { 
      print("Found index: \(indexOfCellString)") 
     } else { 
      print("text not found") 
     } 
    } 
} 
関連する問題