LoginSignup
6
4

More than 5 years have passed since last update.

[Swift3] plistから多次元配列を読み込み、TableViewで表示する。

Last updated at Posted at 2017-01-23

はじめに

plistを使って、tableViewを作成する機会があったので、備忘録として載せます。

plistの作成方法

xcodeの上部タブメニューより、 File>new>file.. >ios > resource の中に、Property List とあるので、クリック。

plistの構成確認

PropertyList.plist  という名で、下記構造のplistを作成しました。

2017-01-24 7.40.14.png

plistの読み込み

    //多次元配列の初期化
    var plistArr = [Dictionary<String, String>]()

    override func viewDidLoad() {
        super.viewDidLoad()

                 //plistを参照
        let path = Bundle.main.path(forResource: "PropertyList", ofType: "plist")

        //参照したplistを、初期化した配列に納入
        plistArr = NSArray(contentsOfFile: path!) as! [Dictionary<String, String>]


    }

tableViewで表示



    //行数指定
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return mathArr.count
    }


    //表示内容
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "[任意]cell", for: indexPath) as![任意]cell

        cell.textLabel?.text = plistArr[indexPath.row]["title"]
        return cell
    }

    //タップ時の処理(例:任意のURLをWebViewControllerで表示)
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tappedCellUrl = plistArr[indexPath.row]["url"]!
        performSegue(withIdentifier: "toWebViewController", sender: nil)

    }



6
4
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
6
4