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

UIRefreshControl使ってみた

Last updated at Posted at 2020-04-02

RXとMVVMでUIRefreshControlを使ってみる。

import系

podfile
import RxSwift

まず、View側にrefreshControlとViewModelのインスタンスを用意

ViewController
var viewModel: HomeViewModel = HomeViewModel()
let refreshControl = UIRefreshControl()

  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    viewModel.tryRefresh(refreshControl: refreshControl,tableView:tableView)
  }

ViewModelに動作系を書く。

ViewModel
import RxSwift
//〜略〜
private var disposeBag = DisposeBag()

  func tryRefresh(refreshControl: UIRefreshControl,tableView: UITableView){
    refreshControl.rx.controlEvent(.valueChanged)
    .subscribe(onNext: {[weak self]_ in
//動かしたいfunctionを呼ぶ。(ネストが嫌ならカスタムしてください。)
      {
       refreshControl.endRefreshing()
       tableView.reloadData()
       }
    }).disposed(by: disposeBag)
  }

これで期待通り動くと思います。
refreshControlはtableで使うよなあ、と思ってこんな感じになったのですが、ご指摘あればコメントください。
MVVMも最近になって勉強を始めた状況なので、使い方変かも。

refleshControlカスタムしたいかたは、ViewControllerに以下のように書いてみてくださいね!

ViewController
///refreshControl
///- Returns:refreshControlerCSS
  func CSSrefleshController(){
//    refreshControl.tintColor = .white ←指定したい色。extensionで色つくってるので、以下のようになっています。
//    refreshControl.attributedTitle = NSAttributedString(string: "入れたいコメント")←これも拡張してるので、以下のようになっている。
    refreshControl.tintColor = Color.main
    refreshControl.attributedTitle = NSAttributedString(string: "Updating".localizedString() ?? "update")
    tableView.addSubview(refreshControl)
  }

上記をdidroadで呼んであげれば完成ー!
拡張の中身なしに書いてしまいましたが、気になる方はコメント頂ければお見せしますー!

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?