auの日記

プログラミング初心者の日記。(auはハンドルネームです)

SwiftのDataSourceとは

auです。

SwiftでTableViewを使う際に、調べているとDelegateとDataSourceを設定しなくてはいけないことを学びました。

DataSourceってなんだろうと疑問に思ったので調べてみました。

DataSourceとは

DataSourceとは、TableViewに表示する内容を提供するものです。

初めてDataSourceを使った際には、エラーで返されてしまいなんだこれと思いましたが、調べてみると「必ず使わなきゃいけないメソッドがある」ということを知りました。

override func viewDidLoad() {
        super.viewDidLoad()
        AudioController.sharedInstance.delegate = self
        tableViewWord.delegate = self
        tableViewWord.dataSource = self
    }
    
    // セルの内容を返すメソッド
    func tableView(_ tableView: UITableView,
                   numberOfRowsInSection section: Int) -> Int {
        return ContryList.count
    }
    // セルの行数を返すメソッド
    func tableView(_ tableView: UITableView,
                   cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "resultCell", for: indexPath)
        let item = ContryList[indexPath.row]
        cell.textLabel?.text = item
        return cell
    }

viewDidLoadでdelegateとdataSourceを、それぞれ紐付けしないといけません。
そして、必須なのはその下の2つのメソッドでした。