はじめに
plistを使って、tableViewを作成する機会があったので、備忘録として載せます。
plistの作成方法
xcodeの上部タブメニューより、 File>new>file.. >ios > resource の中に、Property List とあるので、クリック。
plistの構成確認
PropertyList.plist
という名で、下記構造のplistを作成しました。
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)
}