モケラ

Tech Sheets

mokelab

UICollectionViewでUIRefreshControlを使い、PullToRefreshを実現する

最終更新日:2016-02-21

UICollectionViewでPullToRefreshする例です。UIRefreshControlオブジェクトを生成し、addSubViewするだけなので、ソース全体を示したほうが早いですね。

class RefreshCollectionViewController : UIViewController, UICollectionViewDataSource {
    @IBOutlet var collectionView : UICollectionView?

    override func viewDidLoad() {
        super.viewDidLoad()

        let refreshControl = UIRefreshControl()
        refreshControl.addTarget(self, action: "startLoading:", forControlEvents: UIControlEvents.ValueChanged)
        collectionView?.addSubview(refreshControl)
    }

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

    //MARK: UICollectionView Data source
    // CollectionViewに関する項目なので省略

    //MARK: RefreshControl
    func startLoading(refreshControl : UIRefreshControl) {
        NSThread.detachNewThreadSelector("wait:", toTarget: self, withObject: refreshControl)
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath)
        return cell
    }


    func wait(refreshControl : UIRefreshControl) {
        // 2 sec
        sleep(2)
        dispatch_async(dispatch_get_main_queue()) {
            refreshControl.endRefreshing()
        }
    }
}

一覧に戻る