前提・実現したいこと
とあるサイトからgithubでダウンロードして勉強しています。
当選ですが問題なく動作します。コードを見ると疑問が沸きました。
知りたいこと
(1)XcodeでTableviewを作るには、viewcontorollerクラスにUITableViewDelegate, UITableViewDataSource
を追加(宣言)していきますが、本コードにはありません。
それは、UITableViewControllerクラスを継承しているのだから不要なのでしょうか
(2)いろんな書籍では、UIViewcontrollerクラスから作成しているので、その宣言が必要なのでしょうか
(3)画面にテーブルしか表示しないときはUITableviewを使い、ButtonやLabelを配置して、さらにtableを配置するときにViewcontrollerを使い、上記の宣言をするのでしょうか?
Swiftの本質が理解できていないことを恥じております。教えていただければ幸いですl。
コメントしてある部分は私が書いたものです。内容に誤りがあれば指摘もお願いします。
発生している問題・エラーメッセージ
エラーはありません
該当のソースコード
Swift4
1 2 3import UIKit 4//構造体CellDataを定義 5struct CellData { 6 var opened = Bool() 7 var title = String() 8 var sectionData = [String()] 9} 10 11class TableViewController: UITableViewController { 12 //構造体CellData内容を配列にして変数tableViewDataとしてインスタンス化 13 var tableViewData = [CellData]() 14 15 override func viewDidLoad() { 16 super.viewDidLoad() 17 // Do any additional setup after loading the view, typically from a nib. 18 //配列tableViewDataに内容を入れる 19 tableViewData = [ 20 CellData(opened: false, title: "Title 1", sectionData: ["Cell 1","Cell 2","Cell 3"]), 21 CellData(opened: false, title: "Title 2", sectionData: ["Cell 1","Cell 2","Cell 3","Cell 1","Cell 2","Cell 3"]), 22 CellData(opened: false, title: "Title 3", sectionData: ["Cell 1","Cell 2","Cell 3"])] 23 24 } 25 26 override func didReceiveMemoryWarning() { 27 super.didReceiveMemoryWarning() 28 // Dispose of any resources that can be recreated. 29 } 30 //必須項目、セクションの数 31 override func numberOfSections(in tableView: UITableView) -> Int { 32 return tableViewData.count 33 } 34 //必須項目、セクションの中での行数 35 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 36 /* セクションがopenならセクションデータに1つ多く、それ以外は1つ*/ 37 if tableViewData[section].opened == true { 38 return tableViewData[section].sectionData.count + 1 39 }else{ 40 return 1 41 } 42 } 43 //Cellのデータを1つづつ作成 44 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 45 let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell 46 47 if indexPath.row == 0 { 48 cell.textLabel?.text = tableViewData[indexPath.section].title 49 }else{ 50 cell.textLabel?.text = tableViewData[indexPath.section].sectionData[indexPath.row - 1] 51 } 52 53 return cell 54 } 55 56 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 57 if tableViewData[indexPath.section].opened == true { 58 tableViewData[indexPath.section].opened = false 59 let sections = IndexSet(integer: indexPath.section) 60 tableView.reloadSections(sections, with: .none) 61 }else{ 62 tableViewData[indexPath.section].opened = true 63 let sections = IndexSet(integer: indexPath.section) 64 tableView.reloadSections(sections, with: .none) 65 } 66 } 67 68} 69 70
試したこと
エラーなくビルドできます
補足情報(FW/ツールのバージョンなど)
Xcode9
Swift4
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/09/07 05:41