4

I have an issue with observing the contentOffset property of UITableView with RxCocoa.

I've tried RxCocoa property:

view.tableView.rx.contentOffset
                .mapAt(\.y)
                .subscribe(onNext: { print($0) })

And in console I see (0, 0) once and nothing else.

I've tried to replace it with code from RxCocoa:

ControlProperty(
                values: BehaviorSubject<CGPoint>(value: RxScrollViewDelegateProxy.proxy(for: view.tableView).scrollView?.contentOffset ?? CGPoint.zero),
                valueSink: Binder(view.tableView) { scrollView, contentOffset in
                        scrollView.contentOffset = contentOffset
                    }
                )
                .subscribe(onNext: { print("myOffset", $0) })

And got the same result: myOffset (0, 0) once and nothing else.

I've tried to observe other property and haven't got anything:

view.tableView.rx.didScroll
                .subscribe(onNext: { print(view.tableView.contentOffset) })

BUT. I've tried to add Observable interval:

Observable<Int>.interval(1, scheduler: MainScheduler.instance)
                .subscribe(onNext: { _ in print(view.tableView.contentOffset) })

And each second I've got different points: (0, 0), (0, 38), (0, 64).

I'm using: RxCocoa (5.0.0); RxSwift (5.0.0)

Andrei Krotov
  • 306
  • 1
  • 10

1 Answers1

1

You haven't shown us the code that is actually causing the problem. Note that the below works perfectly:

final class ViewController: UIViewController {
    private var tableView: UITableView!
    private let disposeBag = DisposeBag()

    override func loadView() {
        super.loadView()
        tableView = UITableView(frame: view.bounds)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        view.addSubview(tableView)
    }

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        tableView.frame = view.bounds
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.rx.contentOffset
            .map { $0.y }
            .bind(onNext: { print($0) })
            .disposed(by: disposeBag)

        Observable.just(Array.init(repeating: "Item", count: 35))
            .bind(to: tableView.rx.items) { (tableView, row, element) in
                let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
                cell.textLabel?.text = "\(element) @ row \(row)"
                return cell
            }
            .disposed(by: disposeBag)
    }
}
Daniel T.
  • 32,821
  • 6
  • 50
  • 72