脳汁portal

アメリカ在住(だった)新米エンジニアがその日学んだIT知識を書き綴るブログ

SwiftによるiPhoneアプリ開発入門(超初歩)その9 -リストからの遷移と、編集と削除-

今回は前回作成したセクションに分けたリストに、以下の機能を付け加えます

  • 詳細画面への遷移
  • セルの編集(並び替え)機能
  • セルの削除機能

前回のリスト構造
SwiftによるiPhoneアプリ開発入門(超初歩)その8 -複数セクション(グループ分け)したリスト- - 脳汁portal

完成イメージ
f:id:portaltan:20150726193856p:plain

1、ストーリーボード上のシーンにナビゲーションコントローラを追加

f:id:portaltan:20150726184723p:plain

f:id:portaltan:20150726185310p:plain

2、シーンのNavigation Itemの設定をする

f:id:portaltan:20150726185440p:plain

3、セルのプロパティを編集し、詳細画面への遷移のアイコンを追加

f:id:portaltan:20150726185639p:plain

4、詳細画面のシーンとビューコントローラを作成して対応づける

f:id:portaltan:20150726193214p:plain

f:id:portaltan:20150726193219p:plain

5、詳細画面のシーンにUIImageViewを配置し、DetailViewControllerへアウトレット接続する

f:id:portaltan:20150726190024p:plain

6、詳細画面のビューコントローラを作成
    // 表示する何ファイル名の受けとり
    var imageFileName: String = ""
    
    @IBOutlet weak var imageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 画像を表示
        imageView.image = UIImage(named: imageFileName)
    }
7、一覧画面から詳細画面のシーンへのセグエを接続

f:id:portaltan:20150726190448p:plain

f:id:portaltan:20150726193603p:plain

8、一覧画面のビューコントローラに実装を追加
    override func viewDidLoad() {
        super.viewDidLoad()

        // ナビゲーションバーの右側に編集ボタンを追加
        self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }
9、セルの削除と追加機能を実装する
    // セルの削除と追加を行う
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        
        if editingStyle == .Delete {
            // 削除の場合の処理
            // テーブルビューから削除するだけではなく、必ず実際のデータを先に削除
            items[indexPath.section].removeAtIndex(indexPath.row)
            
            // テーブルビューから、指定した行のデータを削除
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // 挿入の場合の処理
        }
    }
10、セルの移動を行う
    // セルの移動を行う
    override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
        
        // sourceIndexPathの位置にあるデータを削除
        let item = items[sourceIndexPath.section].removeAtIndex(sourceIndexPath.row)
        
        // destinationIndexPathの位置に、削除したデータを追加
        items[destinationIndexPath.section].insert(item, atIndex: destinationIndexPath.row)
    }
11、一覧画面から詳細画面へデータの代入
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        
        let dest = segue.destinationViewController as! DetailViewController
        
        // tableViewプロパティから、選択行のindexPathを取得
        let indexPath: NSIndexPath? = self.tableView.indexPathForSelectedRow()
        
        // 選択行のindexPathが取得できた場合、次の画面にファイル名を渡す
        if let section = indexPath?.section, row = indexPath?.row {
            dest.imageFileName = items[section][row].fileName
        }
    }

ちなみに、

  • as!は強制的に型をキャストして、できなければエラーを返す
  • as?はキャストできなければnilが帰る