概要
UITableViewをスクロールしていき、一番下まで到達したら新しいセルが新たに表示されるようにする。
コード
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
let cellId = "cellId"
var numbers:[String] = ["No.1","NO.2","NO.3","No.4","NO.5","NO.6","No.7","NO.8","NO.9","No.10","NO.11","NO.12"]
var count:Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.delegate = self
tableView.dataSource = self
count = numbers.count
}
}
extension ViewController:UITableViewDelegate,UITableViewDataSource{
//セルの数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numbers.count
}
//セルの登録とラベルの設定
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! TableViewCell
cell.numberLabel.text = numbers[indexPath.row]
return cell
}
//セルの高さ
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
// 現在取得している最後のセルを表示したら新しく10個のセルを追加するメソッド
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == numbers.count - 1 {
while count <= indexPath.row + 10{
numbers.append("No.\(count + 1)")
count += 1
}
self.tableView.reloadData()
}
}
}
//UITableViewCellの指定
class TableViewCell:UITableViewCell{
@IBOutlet weak var numberLabel: UILabel!
}
大切なのはwillDisplayのあたりぐらいですかね。willDisplayメソッドの中で使っているif文は「indexPath.rowがnumbers.count - 1に一致したら{}の中の処理を走らせてね」ってことです。
if文の条件が満たされたらwhile文を使って配列のnumbersに新しく要素を追加することでセルの数を増やしていってます。
まとめ
willDisplayを使えば、Twitterのプロフィール画面みたいにツイートを遡っていくこともできそうですね。私自身初心者なので誤りがあるかもしれませんが、その時はぜひご指摘のほどよろしくお願いいたします。
もしよろしければ使ってみてください。ありがとうございました。