Last active
May 16, 2019 05:29
-
-
Save hgsan/2741165f41c9a0251f2982ab98815c9c to your computer and use it in GitHub Desktop.
manage UIPageControl and UIScrollView with RxSwift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@IBOutlet weak var pageControll: UIPageControl! | |
@IBOutlet weak var scrollView: UIScrollView! | |
var scrollViewPageIndex :Int { | |
set { | |
let contentX = scrollView.width * CGFloat(newValue) | |
DispatchQueue.main.async { | |
UIView.animate(withDuration: 0.2, animations: { [weak self] _ in | |
self?.scrollView.contentOffset = CGPoint.init(x: contentX, y: 0) | |
}) | |
} | |
} | |
get { | |
return Int(scrollView.contentOffset.x / scrollView.width) | |
} | |
} | |
var selectedPageIndex = Variable(Int()) | |
final let bag = DisposeBag() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
setupSubViews() | |
} | |
private func setupSubViews() { | |
selectedPageIndex.asObservable().bindTo(pageControll.rx.currentPage).addDisposableTo(bag) | |
scrollView.rx.contentOffset.bindNext { [weak self] (point:CGPoint) in | |
guard let _ = self?.scrollView.width else { | |
return | |
} | |
if Int(point.x.truncatingRemainder(dividingBy: (self?.scrollView.width)!)) != 0 { | |
return | |
} | |
self?.selectedPageIndex.value = (self?.scrollViewPageIndex)! | |
}.addDisposableTo(bag) | |
} | |
@IBAction func pageControlValueChanged(_ sender: UIPageControl) { | |
scrollViewPageIndex = sender.currentPage | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If anyone wants a more succinct version: