LoginSignup
52
52

More than 5 years have passed since last update.

SwiftでUITableViewミニマムサンプル

Last updated at Posted at 2014-06-06

クラス構成

  • AppDelegate
  • ItemListVC: 一覧ビュー
  • ItemViewCell: セルビュー
  • Item: モデル
AppDelegate.swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        self.window!.backgroundColor = UIColor.whiteColor()
        self.window!.makeKeyAndVisible()

        self.window!.rootViewController = ItemListVC()

        return true
    }
}
ItemListVC.swift
class ItemListVC : UITableViewController, UITableViewDataSource {
    var items: Item[] = Item[]()

    func loadData() {
        for i in 0..100 {
            self.items.append(Item(name: "hoge \(i)"))
        }
    }

    override func loadView() {
        self.loadData()
    }

    override func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return self.items.count
    }

    override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        let item = self.items[indexPath.row]

        let cellId = "ItemViewCell"
        var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? ItemViewCell
        if cell == nil {
            cell = ItemViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:cellId)
        }
        cell?.update(item)
        return cell
    }
}
ItemViewCell.swift
class ItemViewCell : UITableViewCell {
    var item: Item?

    func update(item: Item) {
        self.item = item;
        self.refresh()
    }

    func refresh() {
        self.textLabel.text = self.item?.name
    }
}
Item.swift
class Item {
    var name: String

    init(name: String) {
        self.name = name
    }
}
52
52
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
52
52