m_shige1979のときどきITブログ

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

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

https://github.com/mshige1979

swiftの学習(tableviewによるリスト)

todoアプリとかの事前調査

いくつかサンプルっぽいものを見つけたので実験

プロジェクト作成

シングルページアプリケーションで作成

f:id:m_shige1979:20140928204137p:plain
※特に画面になにか設定を行うわけではない

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

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    var tableview:UITableView?
    var alert = UIAlertView()
    var items = [Dictionary<String, String>]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let screenHeight = UIScreen.mainScreen().bounds.size.height
        let screenWidth = UIScreen.mainScreen().bounds.size.width
        
        self.tableview = UITableView(frame: CGRect(x: 0, y: 60, width: screenWidth, height: screenHeight))
        self.tableview!.dataSource = self
        self.tableview!.delegate = self
        
        self.view.addSubview(self.tableview!)
        
        println("height = \(screenHeight)")
        println("width = \(screenWidth)")
        
        alert.title = "sample"
        alert.addButtonWithTitle("OK")
        
        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){
        alert.message =  items[indexPath.row]["detail"]!
        alert.show()
    }
}
結果

f:id:m_shige1979:20140928204422p:plain

f:id:m_shige1979:20140928204434p:plain

ソースコードだけで実装する場合にやること

tableviewを用意
    var tableview:UITableView?
viewDidLoadで生成
        self.tableview = UITableView(frame: CGRect(x: 0, y: 60, width: screenWidth, height: screenHeight))
viewDidLoadでクラスと紐付け
        self.tableview!.dataSource = self
        self.tableview!.delegate = self
viewDidLoadで画面にtableviewを追加
        self.view.addSubview(self.tableview!)
tableviewを使用するために必要なプロトコルを追加
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
UITableViewDataSource, UITableViewDelegate の使用メソッド
    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){
        alert.message =  items[indexPath.row]["detail"]!
        alert.show()
    }

所感

ソースコードだけで実装するのはちょっと面倒な感じがするけど画面制御を全部コードで行うので管理しやすいと思う。
イベントの追加などはちょっと何が必要であるかがわかりにくいのでこの辺りはいろいろと調べないといけない

長押しとか横にスライドしたりした挙動なども必要になると思うので…

おまけ

GUIの場合

シングルページアプリケーションで作成してtableviewを追加

f:id:m_shige1979:20140928210254p:plain

viewにアイテムを紐付け

f:id:m_shige1979:20140928210515p:plain

ViewController.swiftを編集
//
//  ViewController.swift
//

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableview: UITableView!
    var alert = UIAlertView()
    var items = [Dictionary<String, String>]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        tableview.dataSource = self
        tableview.delegate = self
        
        alert.title = "sample"
        alert.addButtonWithTitle("OK")
        
        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){
        alert.message =  items[indexPath.row]["detail"]!
        alert.show()
    }

}

※あれ?あんまり手間かわってないような…アイテムの設定が直感的になるだけかな?