Swift SnapKit & RxSwift animation

Here is a code snippet of a sample animation with RxSwift and Snapkit. It is not that complicated ...

Swift SnapKit & RxSwift animation

Here is a code snippet of a sample animation with RxSwift and Snapkit. It's not that complicated, but it is interesting to summarize the current state with all the updates on the subject.

As a reminder:

  • RxSwift: Rx is a generic abstraction of computation expressed through Observable interface. This is a Swift version of Rx.
  • Snapkit: SnapKit is a DSL to make Auto Layout easy on both iOS and OS X.

We will see how to move an object from point A to B. Simple, but sufficient to animate a logo, for example :). We'll assume that you already know how to use rxSwift. This example is based on our Stack Swift.

1/ Define the element

// we user Then.swift for easy declaration

let logo1 = UIImageView().then {
    $0.contentMode = .scaleAspectFit
    $0.alpha = 1
    $0.UIImage(named: "logo1")
}

// edited constraint
var rightLogo1: Constraint?

2/ Add it

override func viewDidLoad() {
    super.viewDidLoad()
    self.logo1.image = UIImage(named: "logo1")
}

3/ Define these constraints

// called once during override updateViewConstraints

override func setupConstraints() {
    self.width = self.view.frame.width
    // logo
    self.logo1.snp.makeConstraints { make in
        make.top.equalTo(self.view).inset(40)
        make.width.height.equalTo(width/3)
        // save start constraint status
        self.rightLogo1 = make.centerX.equalTo(self.view).offset(width).constraint
}

4/ Animate when your state is ready (for example)

func bindState(_ reactor: OnboardingReactor) {
    reactor.state
        .debounce(.milliseconds(1000), scheduler: MainScheduler.instance)
        .take(1)
        .subscribe(onNext: { _ in
            self.rightLogo1?.update(offset: 0)
            UIView.animate(withDuration: 0.75, animations: { self.view.layoutIfNeeded() }, completion: nil)
        })
        .disposed(by: self.disposeBag)
}

That's it 🚀 !