UITableViewのswiftサンプルコードから学ぶ


**このメモはswiftもUIKitについてもほぼ知識ゼロな人が勉強のメモとして書いています。色々間違っている可能性があるので、ご注意下さい**

#UITableViewの種類

- UITableViewは二種類ある。１つがセルが固定されているStatic Cellsで、もう一つがセルの数が可変なDynamic Prototypes
- 下のスクリーンショットの右の方のContentってラベルのプルダウンのメニューでタイプを変更できる

![UITableView_Content.png](https://qiita-image-store.s3.amazonaws.com/0/13615/32285d45-33cc-4ed2-8293-175ef37f3ab9.png "UITableView_Content.png")


>When you configure the attributes of a table view in the storyboard editor, you choose between two types of cell content: static cells or dynamic prototypes.

>Static cells. Use static cells to design a table with a fixed number of rows, each with its own layout. Use static cells when you know what the table looks like at design time, regardless of the specific information it displays.

>Dynamic prototypes. Use dynamic prototypes to design one cell and then use it as the template for other cells in the table. Use a dynamic prototype when multiple cells in a table should use the same layout to display information. Dynamic prototype content is managed by the data source at runtime, with an arbitrary number of cells.


[About Table Views in iOS Apps](https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/TableView_iPhone/AboutTableViewsiPhone/AboutTableViewsiPhone.html)

#対象のサンプルコード

```swift:ViewController.swift
import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!
    
    var texts = ["one", "two", "three"];
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        tableView.delegate = self
        tableView.dataSource = self
    }

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

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return texts.count
    }

    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
    }
}
```

#ViewControllerが継承しているクラスの説明

```switf
import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
```

## UIViewController

>In an iOS app, you use a view controller (UIViewController) to manage a content view with its hierarchy of subviews.

>Each content view hierarchy that you build in your storyboard needs a corresponding view controller, responsible for managing the interface elements and performing tasks in response to user interaction.

>View controllers play many roles. They coordinate the flow of information between the app’s data model and the views that display that data, manage the life cycle of their content views, and handle orientation changes when the device is rotated. But perhaps their most obvious role is to respond to user input.

https://developer.apple.com/library/ios/referencelibrary/GettingStarted/RoadMapiOS/DefiningtheInteraction.html#//apple_ref/doc/uid/TP40011343-CH7-SW1

## UITableViewDelegate

>The delegate is responsible for dealing with user interactions, or customizing the display of certain entries.

[Cocoa and Cocoa Touch Define a Large Number of Protocols](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithProtocols/WorkingwithProtocols.html)

>The delegate of a UITableView object must adopt the UITableViewDelegate protocol. Optional methods of the protocol allow the delegate to manage selections, configure section headings and footers, help to delete and reorder cells, and perform other actions.

[UITableViewDelegate - iOS Developer Library](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDelegate_Protocol/)

## UITableViewDataSource

>The UITableViewDataSource protocol is adopted by an object that mediates the application’s data model for a UITableView object. The data source provides the table-view object with the information it needs to construct and modify a table view.

[UITableViewDataSource Protocol Reference](https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UITableViewDataSource_Protocol/index.html)

## Protocolとは?

>In the real world, people on official business are often required to follow strict procedures when dealing with certain situations. Law enforcement officials, for example, are required to “follow protocol” when making enquiries or collecting evidence.

>In the world of object-oriented programming, it’s important to be able to define a set of behavior that is expected of an object in a given situation. As an example, a table view expects to be able to communicate with a data source object in order to find out what it is required to display. This means that the data source must respond to a specific set of messages that the table view might send.

[Working with Protocols - Programming with Objective-C, iOS Developer Library](https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithProtocols/WorkingwithProtocols.html)

>A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol doesn’t actually provide an implementation for any of these requirements—it only describes what an implementation will look like.

[Protocols](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html)

## SwiftでObject-Cで定義されたprotocolを使う方法

>In Swift, you can adopt protocols that are defined in Objective-C. Like Swift protocols, any Objective-C protocols go in a comma-separated list following the name of a class’s superclass, if any.

>SWIFT

>class MySwiftViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    // define the class
}

>Objective-C protocols come in as Swift protocols. If you want to refer to the UITableViewDelegate protocol in Swift code, refer to it as UITableViewDelegate (as compared to id<UITableViewDelegate> in Objective-C).

>Because the namespace of classes and protocols is unified in Swift, the NSObject protocol in Objective-C is remapped to NSObjectProtocol in Swift.

[Writing Swift Classes with Objective-C Behavior](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WritingSwiftClassesWithObjective-CBehavior.html)

#ViewControllerが実装しているメッソッド

## func viewDidLoad()

- UIViewControllerのメソッドをオーバーライドしている
- ViewControllerの初期化時に呼ばれるメソッド
- サンプルコードではtableViewメンバ変数の初期化を行っている
- UITableViewDelegate, UITableViewDataSourceの継承をViewControllerが行っているためselfをセットしているが、当該クラスを継承したオブジェクトならViewControllerに限る必要はない


```swift
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        tableView.delegate = self
        tableView.dataSource = self
    }
```

>This method is called after the view controller has loaded its view hierarchy into memory. This method is called regardless of whether the view hierarchy was loaded from a nib file or created programmatically in the loadView method. You usually override this method to perform additional initialization on views that were loaded from nib files.

[UIViewController Class Reference](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/index.html#//apple_ref/occ/instm/UIViewController/viewDidLoad)

## func didReceiveMemoryWarning()

- メモリ不足の際にシステムから呼ばれるメソッド
- 呼ばれた際は不要なリソースを解放するようなコードを書いておく
- 今回のサンプルコードでは特に解放できそうなリソースがないので特に何も書いていない

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

```

>Sent to the view controller when the app receives a memory warning.

[UIViewController Class Reference](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/index.html#//apple_ref/occ/instm/UIViewController/didReceiveMemoryWarning)

## func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int

- UITableViewDataSourceのProtocolによって実装が要求されるメソッド
- 指定されたセクション(section)のrowの数を戻り値として返す

```switf
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return texts.count
    }
```

> Tells the data source to return the number of rows in a given section of a table view.

[UITableViewDataSource Protocol Reference](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDataSource_Protocol/#//apple_ref/occ/intfm/UITableViewDataSource/tableView:numberOfRowsInSection:)

## func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->  UITableViewCell 

- UITableViewDataSourceのProtocolによって実装が要求されるメソッド
- 指定されたIndexPathに対するUITableViewCellインスタンスを返すメソッド

```swift
    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
    }
```

### NSIndexPathとは

- section, row(共にInt型)等のプロパティを持つクラス

>The UIKit framework adds programming interfaces to the NSIndexPath class of the Foundation framework to facilitate the identification of rows and sections in UITableView objects and the identification of items and sections in UICollectionView objects.

[NSIndexPath](https://developer.apple.com/library/ios/documentation/UIKit/Reference/NSIndexPath_UIKitAdditions/index.html)

#UITableViewについて調べる際に参考になりそうな記事

http://dev.classmethod.jp/smartphone/iphone/storyboard_uitableview/
http://dev.classmethod.jp/smartphone/iphone/search_uitableview/
http://dev.classmethod.jp/smartphone/iphone/uitableview_custom_cell/
http://dev.classmethod.jp/smartphone/uitableview_navigationcontroller/
http://blog.teamtreehouse.com/introduction-to-the-ios-uitableviewcontroller