1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TableViewでハマったこと

Last updated at Posted at 2019-09-08

swift:TableView

TableViewは設定をミスると一生表示されないどころかAppDelegateで落ちてしまうので要注意です。

スクリーンショット 2019-09-08 8.32.18.png

まず普通にstoryboardからTableViewをセットします。

でコードも書いていきます。

sample.swift
import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    let sampleList = ["にんじん","じゃがいも","豚肉","ルー"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sampleList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell :UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath)
        cell.textLabel!.text = sampleList[indexPath.row]
        return cell
    }
}

ソースはこれで特に問題ないですがこれでは何も表示されません。

スクリーンショット 2019-09-08 8.41.51.png

ここから設定を変更すれば表示されます。

スクリーンショット 2019-09-08 8.43.25.png

まずここのdataSourceとdelegateの設定をします。
どうするかと言うと、、、

スクリーンショット 2019-09-08 8.54.55.png

そして次にIdentifierを設定します。

スクリーンショット 2019-09-08 8.56.35.png

今回

sample.swift
let cell :UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath)

withIdentifier: "cell"なのでIdentifierは同じくcellに設定します。

これで表示がされるはずです。

スクリーンショット 2019-09-08 8.59.54.png

うまくできました。

設定もした上でソースを書いていくことを忘れないようにしないといけませんね。

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?