Swiftで複数のTableViewを使うことができた
auです。
Swiftを使って開発をしているのですが、複数のTableViewがほしいと思うようになりました。
カスタムセルを使えば、同じようなことができるのかなと思ったのですが、今回は並列でTableViewを設置して使いたかったので、少し違うかなということでやめました。
完成はこんな感じで、下にTableViewが二つあり、別々に値を挿入できるような感じです。
やり方は、文字で書くと単純です。
TableViewにTagの番号を振り、その番号で、どちらのテーブルを扱うかを判定するような感じです。
TableViewにはもちろん、TableViewCellを持っています(Identifiewを任意の名前に設定する)
TagはViewの中の値を変更(0と1)
chechTableView(自作メソッド)を使って、Tagの値によって状態を変化させます。
var tag: Int = 0 var cellIdentifier: String = "" var items = [[String]]() // 2次元配列で初期化 @IBOutlet weak var tableViewWord: UITableView! @IBOutlet weak var selectTableView: UITableView! // 最初に呼ばれるメソッド override func viewDidLoad() { super.viewDidLoad() tableViewWord.delegate = self tableViewWord.dataSource = self selectTableView.delegate = self selectTableView.dataSource = self // 空の配列を追加 items.append([]) items.append([]) } // 処理を分岐するメソッド func checkTableView(_ tableView: UITableView) -> Void{ if (tableView.tag == 0) { tag = 0 cellIdentifier = "resultCell" } else if (tableView.tag == 1) { tag = 1 cellIdentifier = "selectCell" } } // セルの行数 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { checkTableView(tableView) // tagの番号によって行数を設定 return items[tag].count } // セルの中身を設定 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { checkTableView(tableView) // どのTableViewCellを対象にするか決めている let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) cell.textLabel?.text = items[tag][indexPath.row] return cell }
TableViewを扱うのに必須なメソッドもあると長く見えますが、実装してみたら単純でした。
それでも慣れるのに3時間くらいかかりました。