メインコンテンツへスキップ
見出し画像

【徒然iOS】気ままにUIKit21〜TableViewのセクションとインデックス〜

    概要

    このマガジンは四十を過ぎたおっさんが、

    を参考にStoryboardでiOSアプリを完全に趣味で楽しんでいるだけな記事を気ままに上げてます。

    今回

    をやる〜〜〜!

    前準備

    1. 念の為、バックアップ

    2. 新しいクラス

    3. ビューコントローラの追加

    4. イニシャルビューの変更

    をいつも通りやってから本題へ💃

    画像
    こんな感じ💦

    本題

    ⒈テーブルビューを設置して、data Source連携

    画像
    ここは〜〜〜
    画像
    前回と一緒〜〜〜

    ⒉Table Viewをクリックし、設定項目のPrototype Cellsを1に変更して、テーブルビューの下にTable View Cellを追加

    画像
    ここも前回と一緒〜〜〜

    ⒊Table View CellをクリックしたあとにIdentifierにTestCellを入力

    ここは、前回のビューで使ったから、TestCell2にしてみよう

    画像
    IdentifierをTestCell2に〜〜〜

    * Styleを「Grouped」に変え、ビューテーブルのサイズを少し大きく

    画像
    こんな感じかな

    ⒋ コード追加

    以下のコードを追加

        //データ
        var dataInSection = [["青山","阿部"], ["加藤","川島","神田"], ["佐藤","坂田"], ["田中"]]
     
        //セクション
        var sectionIndex:[String] = ["あ行", "か行", "さ行", "た行"]
        
        //データを返す
        func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCellWithIdentifier("TestCell", forIndexPath:indexPath) as UITableViewCell
            var test = dataInSection[indexPath.section]
            cell.textLabel?.text = test[indexPath.row]
            return cell
        }
     
        //データの個数を返す
        func tableView(tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
            return dataInSection[section].count
        }
     
        //セクション名を返す
        func tableView(tableView:UITableView, titleForHeaderInSection section:Int) -> String?{
            return sectionIndex[section]
        }
     
        //セクションの個数を返す
        func numberOfSectionsInTableView(tableView: UITableView) -> Int {
            return sectionIndex.count
        }
    画像
    前回と同じエラーが発生してる様子👀

    前回同様にエラーを修正してみる

    * 修正後のコード

        //データ
        var dataInSection = [["青山","阿部"], ["加藤","川島","神田"], ["佐藤","坂田"], ["田中"]]
        //セクション
        var sectionIndex:[String] = ["あ行", "か行", "さ行", "た行"]
        //データを返す
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            var cell = tableView.dequeueReusableCell(withIdentifier: "TestCell2", for:indexPath) as UITableViewCell
            var test = dataInSection[indexPath.section]
            cell.textLabel?.text = test[indexPath.row]
            return cell
        }
        //データの個数を返す
        func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int {
            return dataInSection[section].count
        }
        //セクション名を返す
        func tableView(_ tableView:UITableView, titleForHeaderInSection section:Int) -> String?{
            return sectionIndex[section]
        }
        //セクションの個数を返す
        func numberOfSectionsInTableView(tableView: UITableView) -> Int {
            return sectionIndex.count
        }

    ⒌シミュレータで実行

    画像
    あ行しか出てこないね💦

    既に、やり方が変わっているのかな?
    なぜ、できないんだろう、、、
    と、ネットで検索してみて、、、

    ではやり方が違いすぎる

    日付も最新だし、これで見てみると、、、

    // セクションの数
        func numberOfSections(in tableView: UITableView) -> Int {
            return sectionTitle.count
        }

    の記載あり、、、ん?

    ⒍JumptoDefinitionを確認

    画像
    ん?、、、あ💦

    JumptoDefinition

    @available(iOS 2.0, *)
        optional func numberOfSections(in tableView: UITableView) -> Int // Default is 1 if not implemented

    追加したコード

     //セクションの個数を返す
        func numberOfSectionsInTableView(tableView: UITableView) -> Int {
            return sectionIndex.count
        }

    エラー警告は出てないけど、書き方が変わってる

    ⒎コード変更

    class TableView2Controller: UIViewController, UITableViewDataSource {
        
        //データ
        var dataInSection = [["青山","阿部"], ["加藤","川島","神田"], ["佐藤","坂田"], ["田中"]]
        //セクション
        var sectionIndex:[String] = ["あ行", "か行", "さ行", "た行"]
        //セクション名を返す
        func tableView(_ tableView:UITableView, titleForHeaderInSection section:Int) -> String?{
            return sectionIndex[section]
        }
        //セクションの個数を返す
        func numberOfSections(in tableView: UITableView) -> Int {
            return sectionIndex.count
        }
        //データを返す
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "TestCell2", for:indexPath) as UITableViewCell
            let test = dataInSection[indexPath.section]
            cell.textLabel?.text = test[indexPath.row]
            return cell
        }
        //データの個数を返す
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return dataInSection[section].count
        }
        
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    }
    

    ⒏再度、シミュレータを実行

    画像
    出てきた〜〜〜〜〜🕺

    ⒐インデックスも追加してみよう

        //セクション名の配列を返す
        func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
            return sectionIndex
        }

    を追加して〜〜〜〜
    シミュレータを実行すると、、、

    画像
    出てこないね

    とここで焦らず〜〜〜
    再度、JumptoDefinitionでsectionIndexTitlesを検索

        @available(iOS 2.0, *)
        optional func sectionIndexTitles(for tableView: UITableView) -> [String]?

    書き方が変わってる👀

    どうやら、
    シンタックスに忠実に

    inとかforを含めて、()の中に入れる
    👉TableViewなんかの重複を省く
    =よりモダンに直感的
    =Swiftのコード思想

    な書き方に変わってるみたいだね💦

    なので、忠実に
    以下に書き換え

    class TableView2Controller: UIViewController, UITableViewDataSource {
        
        //データ
        var dataInSection = [["青山","阿部"], ["加藤","川島","神田"], ["佐藤","坂田"], ["田中"]]
        //セクション
        var sectionIndex:[String] = ["あ行", "か行", "さ行", "た行"]
        //セクション名を返す
        func tableView(_ tableView:UITableView, titleForHeaderInSection section:Int) -> String?{
            return sectionIndex[section]
        }
        //セクションの個数を返す
        func numberOfSections(in tableView: UITableView) -> Int {
            return sectionIndex.count
        }
        //データを返す
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "TestCell2", for:indexPath) as UITableViewCell
            let test = dataInSection[indexPath.section]
            cell.textLabel?.text = test[indexPath.row]
            return cell
        }
        //データの個数を返す
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return dataInSection[section].count
        }
        
        //セクション名の配列を返す
        func sectionIndexTitles(for tableView: UITableView) -> [String]? {
            return sectionIndex
        }
        
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    }

    シミュレータを実行し直すと、、、

    画像
    出てきた!
    ちゃんとインデックスも反応することを確認ずみ〜〜〜〜🕺

    恒例のブラッシュアップ

    前々回までしばらくAutoLayoutだったので、省いていたけど
    ちゃんと動いたことを確認できたので、前回のヤツも含めてブラッシュアップをしとこう!

    前回分

    画像
    テーブルビュー全体の大きさを目一杯に広げて、制約を付ける
    画像
    制約が追加されたのでシミュレータで実行
    画像
    👀らしくなったけど、データが少ないからちょっと寂しい

    なので、リストのデータを追加💃

    画像
    こんな感じかな
    class TableViewController: UIViewController, UITableViewDataSource {
        
        //表示データ
        var dataList = ["青山","阿部", "加藤","川島","神田","佐藤","坂田", "田中","千種","津崎","手嶋","中原","西山","羽鳥","平家","間宮","水野","武藤","元山","矢野",]
        
        //データを返すメソッド(スクロールなどでページを更新する必要が出るたびに呼び出される)
        //自動追加されたstubs
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "TestCell", for:indexPath) as UITableViewCell
            cell.textLabel?.text = dataList[indexPath.row]
            return cell
        }
        
        //データの個数を返すメソッド
        //自動追加されたstubs
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return dataList.count
        }
        
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    }

    今回分

    同様に、

    画像
    広げて制約追加
    画像
    追加後〜〜〜
    画像
    やっぱり寂しいので、、、データ追加
    画像
    あ行をクリック
    画像
    や行をクリック

    変更後のコード

    //前回
    class TableViewController: UIViewController, UITableViewDataSource {
        
        //表示データ
        var dataList = ["青山","阿部", "加藤","川島","神田","佐藤","坂田", "田中","千種","津崎","手嶋","中原","西山","羽鳥","平家","間宮","水野","武藤","元山","矢野",]
        
        //データを返すメソッド(スクロールなどでページを更新する必要が出るたびに呼び出される)
        //自動追加されたstubs
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "TestCell", for:indexPath) as UITableViewCell
            cell.textLabel?.text = dataList[indexPath.row]
            return cell
        }
        
        //データの個数を返すメソッド
        //自動追加されたstubs
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return dataList.count
        }
        
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    }
    
    //今回
    class TableView2Controller: UIViewController, UITableViewDataSource {
        
        //データ
        var dataInSection = [["青山","阿部"], ["加藤","川島","神田"], ["佐藤","坂田"], ["田中","千種","津崎","手嶋"],["中原","西山"],["羽鳥","平家"],["間宮","水野","武藤","元山"],["矢野"]]
        //セクション
        var sectionIndex:[String] = ["あ行", "か行", "さ行", "た行","な行", "は行", "ま行", "や行"]
        //セクション名を返す
        func tableView(_ tableView:UITableView, titleForHeaderInSection section:Int) -> String?{
            return sectionIndex[section]
        }
        //セクションの個数を返す
        func numberOfSections(in tableView: UITableView) -> Int {
            return sectionIndex.count
        }
        //データを返す
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "TestCell2", for:indexPath) as UITableViewCell
            let test = dataInSection[indexPath.section]
            cell.textLabel?.text = test[indexPath.row]
            return cell
        }
        //データの個数を返す
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return dataInSection[section].count
        }
        
        //セクション名の配列を返す
        func sectionIndexTitles(for tableView: UITableView) -> [String]? {
            return sectionIndex
        }
        
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    }

    まとめ

    いやあ、エラーも出さずに、stubsでも自動的に追加されずに、結構、書き方が変わってるメソッドが多いな💦

    でも触れはしたけど、やはり、

    💃Jump to Definitionは友達!!!
    困った時は、まずはコイツに聞こう🕺
    (参考にした他の記事だとDelegate必須みたいな書き振りだったけど、今回のコードだと、Delegateなしで行けたしね💦
    データソースを他から呼び出してないから、実は当たり前なんだけど)

    しっかし、

    記事の内容的には、そんなに長くなかったけど、異様に長くなってしまった💦
    変更点がたくさんあるから、進化し続ける言語だねえ。Swift💦
    と言いつつ、やっぱり、

    相違点がわかるし、振り返りながらの開発は楽しい🎶
    解決できて、新しい発見ができてよかった〜〜〜〜!

    Apple公式

    さて、次回は

    をやる〜〜〜〜!
    今回が長くなったので、明日はとりあえず休んで、明後日以降で時間ができたら再開〜〜〜!

     
     
    タダの道楽者💫ネガティブなコメント一切お断り 裾野が広がりゃそれで良い 洋書と古典とSwiftをこよなく愛するオッさん👀 色即是空🕺 記事はマガジンの方が読みやすいかな💦 ちょい難とダラダラ💃 無駄な対立軸と課題探し思考は要らんな。 変幻自在➕縦横無尽➕融通無碍🟰天衣無縫

    あなたへのおすすめ