teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

2

plistファイルのパースに PropertyListDecoder を使用するサンプルの追加

2020/08/16 12:08

投稿

ch3cooh
ch3cooh

スコア287

answer CHANGED
@@ -79,4 +79,77 @@
79
79
 
80
80
  ![イメージ説明](449ca4e022d036ebdae6334db3565b9b.png)
81
81
 
82
- データの取り出し方が変わりますのでご注意ください。
82
+ データの取り出し方が変わりますのでご注意ください。
83
+
84
+ ---
85
+
86
+ 追記2
87
+
88
+ > >セクションごとの名前とデータを持つことができます。
89
+ > >データの取り出し方が変わりますのでご注意ください。
90
+ > この場合、セルに表示する「Name」と「Image」を取得する際に、「セクション1」の中の「Name」と「Image」…と指定するということですかね。
91
+
92
+ それで良いと思います!
93
+
94
+ 質問の内容からは大きく離れてしまいますが、もし私が実装するとすれば データの取り出し方には Decodable を使うかと思います。
95
+
96
+ ```swift
97
+ struct HogeItem: Decodable {
98
+ let name: String
99
+ let imageName: String
100
+ }
101
+
102
+ struct HogeSection: Decodable {
103
+ let name: String
104
+ let items: [HogeItem]
105
+ }
106
+
107
+ var _items: [HogeSection] = []
108
+ ```
109
+
110
+ データ表示は下記のように書くことができます。
111
+
112
+ ```swift
113
+ override func viewDidLoad() {
114
+ super.viewDidLoad()
115
+
116
+ // Plistファイルパス
117
+ if let path = Bundle.main.path(forResource: "hoge", ofType:"plist" ) {
118
+ let data = try! Data(contentsOf: URL(fileURLWithPath: path))
119
+ _items = try! PropertyListDecoder().decode([HogeSection].self, from: data)
120
+ }
121
+ //...省略
122
+ }
123
+
124
+ // 設定
125
+ func numberOfSectionsInTableView(tableView: UITableView) -> Int {
126
+ return _items.count
127
+ }
128
+
129
+ // 設定(行数)
130
+ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
131
+ return _items[section].items.count
132
+ }
133
+
134
+ // 設定(セクションタイトル)
135
+ func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
136
+ return _items[section].name
137
+ }
138
+
139
+ // 設定(セル)
140
+ func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
141
+ let item = _items[indexPath.section].items[indexPath.row]
142
+
143
+ let cell = tableView.dequeueReusableCell(withIdentifier: "DisneyCell", for: indexPath as IndexPath)
144
+ cell.textLabel?.text = item.name
145
+ cell.imageView?.image = UIImage(named: item.imageName)
146
+ return cell
147
+ }
148
+
149
+ //セルタップ時にセルの内容を取得する
150
+ func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
151
+ let item = _items[indexPath.section].items[indexPath.row]
152
+
153
+ print(item.name)
154
+ }
155
+ ```

1

セクション名もplistで定義する方法を追記しました

2020/08/16 12:08

投稿

ch3cooh
ch3cooh

スコア287

answer CHANGED
@@ -67,4 +67,16 @@
67
67
 
68
68
  print(item.name)
69
69
  }
70
- ```
70
+ ```
71
+
72
+ ---
73
+
74
+ 追記
75
+
76
+ > セクション名をplistで指定することは可能でしょうか?
77
+
78
+ 可能です。下記のようにplistを定義すれば、セクションごとの名前とデータを持つことができます。
79
+
80
+ ![イメージ説明](449ca4e022d036ebdae6334db3565b9b.png)
81
+
82
+ データの取り出し方が変わりますのでご注意ください。