LoginSignup
57
59

More than 5 years have passed since last update.

SwiftでのTableView データ表示編

Last updated at Posted at 2015-08-30

Swiftでの簡単なテーブルビュー

やること

  1. StoryBoardのViewControllerにTableViewを追加
  2. StoryBoardのTableViewをViewControllerにIBOutlet接続(名前をtableViewと設定)
  3. UITableViewDataSourceとUITableViewDelegateを追加
  4. delegateとdataSourceをselfに設定
  5. セルに表示するテキストを追加
  6. 必要なtableViewメソッドを2つ追加
  7. セルタップ次の動作を追加
ViewController
import UIKit

// 3. UITableViewDataSourceとUITableViewDelegateを追加する
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    // 2. StoryBoardとつなぐ
    @IBOutlet weak var tableView: UITableView!

    // 5. テーブルに表示するテキスト
    let texts = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

    override func viewDidLoad() {
        super.viewDidLoad()

        // 4. delegateとdataSourceを設定
        tableView.delegate = self
        tableView.dataSource = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // 6. 必要なtableViewメソッド
    // セルの行数
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return texts.count
    }

    // 6. 必要なtableViewメソッド
    // セルのテキストを追加
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")

        cell.textLabel?.text = texts[indexPath.row]
        return cell
    }

    // 7. セルがタップされた時
    func tableView(table: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) {
        println(texts[indexPath.row])
    }

}

参考ソース
https://github.com/senseiswift/tableviewtest/blob/master/tableviewtest/ViewController.swift

続きはこちら SwiftでのTableView データ表示編
http://qiita.com/senseiswift/items/20d09c523772caaf8005

57
59
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
57
59