LoginSignup
41
42

More than 5 years have passed since last update.

TableViewをPullして値を更新する方法(Pull to Refresh)

Last updated at Posted at 2014-11-30

Twitterなどにある、TableViewを下に引っ張るとクルクル回り、更新をしてくれる処理がAdd Pull to Refresh to Table View in iOS8 with Swiftにありましたので、それをStoryBoardを使わずに実装しました。この例では配列の値を逆順にすることをしています。

環境

OX 10.10
Xcode 6.1 (6A1046a)

コード

ViewController.swift
import UIKit

class ViewController: UITableViewController {
    var alphabet = ["A","B","C","D","E","F","G","H","I"]

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView = UITableView()
        self.tableView.frame = CGRect(x: 0.0, y: 0.0, width: self.view.bounds.width, height: self.view.bounds.height)
        self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")

        var refreshControl = UIRefreshControl()
        refreshControl.addTarget(self, action: Selector("sortArray"), forControlEvents: UIControlEvents.ValueChanged)
        self.refreshControl = refreshControl
    }

    // alphabetを逆順にする。
    func sortArray() {
        var sortedAlphabet = alphabet.reverse()

        for (index, element) in enumerate(sortedAlphabet) {
            alphabet[index] = element
        }

        self.tableView.reloadData()
        self.refreshControl?.endRefreshing()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Return the number of rows in the section.
        return alphabet.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

        // Configure the cell...
        cell.textLabel?.text = alphabet[indexPath.row]
        return cell
    }
}

UITableViewControllerを使わずに,UIViewControllerとUITableViewで初めは実装をした(参考: http://qiita.com/ktsujichan/items/5d69c6ac1c4ddb109247) のですが、うまくいかなかったので今回はこの書き方で。

41
42
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
41
42