選択した時の状態を保持したかったので、Structの配列でモデルを作成しました。
セルを選択した時に呼ばれるデリゲートメソッドdidSelectRowAt
でモデルの選択状態を変更して リロードすると文字が変わります。
swift
1import UIKit
2
3class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
4
5 @IBOutlet weak var tableView: UITableView!
6 // Data Array
7 var dataArray: Array<DataModel> = []
8
9 override func viewDidLoad() {
10 super.viewDidLoad()
11
12 // データを作成
13 createData()
14
15 tableView.estimatedRowHeight = 44
16 tableView.rowHeight = UITableViewAutomaticDimension
17 }
18
19 func createData() {
20 for i in 0...10 {
21 dataArray.append(DataModel(part: "part -- \(String(i))", pass: "pass ** \(String(i))"))
22 }
23 }
24
25 // MARK: - TableView Delegate & DataSource
26
27 // Row Count
28 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
29 return dataArray.count
30 }
31
32 // Generate Cell
33 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
34 let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
35 let data = dataArray[indexPath.row]
36
37 // データの選択状態でpartかpassの文字列を出し分ける
38 cell.textLabel?.text = data.isSelectPass ? data.pass : data.part
39 return cell
40 }
41
42 // Select Cell
43 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
44 tableView.deselectRow(at: indexPath as IndexPath, animated: true)
45
46 // データの選択状態を変更してテーブルをリロード
47 dataArray[indexPath.row].selectChange()
48 tableView.reloadData()
49 }
50}
51
52
53// partとpassを持つデータ
54struct DataModel {
55
56 var part: String!
57 var pass: String!
58 var isSelectPass = false
59
60 init(part: String = "", pass: String = "", isSelectPass: Bool = false) {
61 self.part = part
62 self.pass = pass
63 self.isSelectPass = isSelectPass
64 }
65
66 mutating func selectChange() {
67 self.isSelectPass = !self.isSelectPass
68 }
69}
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/10/08 12:38