m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

swiftの学習(xcodeのNavigationController)

概要

ヘッダーにナビゲーションを付与して戻る処理を完結にする
毎回unwind記載しないでもいいように

実装

GUI設定

f:id:m_shige1979:20141013154313p:plain

ViewController.swift
//
//  ViewController.swift
//

import UIKit

class ViewController: UIViewController {
    
    var items = [Dictionary<String, String>]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        items.append(
            [
                "name": "りんご",
                "detail": "テスト1"
            ]
        )
        
        items.append(
            [
                "name": "みかん",
                "detail": "テスト2"
            ]
        )
        
        items.append(
            [
                "name": "すいか",
                "detail": "テスト3"
            ]
        )
        
        items.append(
            [
                "name": "めろん",
                "detail": "テスト4"
            ]
        )

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        // リストの件数を返す1
        return  items.count
    }
    
    // セルをitemsから設定する処理
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")!
        cell.textLabel?.text = items[indexPath.row]["name"]!
        cell.detailTextLabel?.text = items[indexPath.row]["detail"]
        return cell;
    }
    
    // セルをクリックした時に発生するイベント
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        performSegueWithIdentifier("page1", sender: self)
    }


}
遷移先の画面を追加して、ヒモ付

f:id:m_shige1979:20141013155339p:plain
※showに設定

ナビゲーションを追加

f:id:m_shige1979:20141013155401p:plain

ナビバーに設定

f:id:m_shige1979:20141013161543p:plain

結果

f:id:m_shige1979:20141013162033g:plain

所感

これは結構簡単でした。
画面遷移自体がこれで楽になるイメージ。
モーダルフォームとかの場合は多少工夫は必要ですけど、ナビゲーションバーを出すので戻り方が直感的になる。