0
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 3 years have passed since last update.

[Swift] UITableViewで無限スクロールを実装する方法[初心者用]

Posted at

概要

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のプロフィール画面みたいにツイートを遡っていくこともできそうですね。私自身初心者なので誤りがあるかもしれませんが、その時はぜひご指摘のほどよろしくお願いいたします。
もしよろしければ使ってみてください。ありがとうございました。

0
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
0
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?