iOS animations with NSLayoutConstraint, in swift 4 & Xcode 10
Hello everyone, I have tried some simple iOS animation with NSLayoutConstraint in Swift 4. Here is the animation,
You can find the video tutorials here — Swift Dynamics
Lets get into the code. Please download the starter app from here . The starter app contains two UIViews and one imageView at the center.
First I will open the Main.storyboard
and add height
and width
constraints for the imageView. after that add the horizontal
and vertical
constraints.
Now we will add the constraints for top Orange view
. I have added leading , trailing and top constraint to 0
.
Add the bottom
constraint to the imageView's
vertical spacing.
Now add the leading
trailing
and bottom
constraints for the second view.
Add the top constraint to the imageView's
vertical spacing.
Open the assistant Editor
and create a reference for the imageView.
Crate a reference for the vertical
constraint of the imageView
.
Open the ViewController.swift
and create two more variables
var minHeight:CGFloat = 0.0
var viewCenter:CGFloat = 0.0
The minHeight
is the maximum value to which we can scroll vertically (top or bottom). viewCenter
is the center of the view.
Here the catch is to restrict pan gesture movement only in vertical direction. So, I am going to write an extension of the UIPanGestureRecognizer
.Inside that we will override the touchsMoved(_ touches: _ event: )
function . This method will get called each time we drag the imageView
. Inside this function we have to calculate the velocity
of the drag . From the velocity we can check whether the movement is in horizontal
or vertical
. If the velocity.x
value is greater than the velocity.y
value, then we will cancel the movement. here is the final code,
class PanDirectionGestureRecognizer: UIPanGestureRecognizer {
init(target: AnyObject, action: Selector) {
super.init(target: target, action: action)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesMoved(touches, with: event)
if state == .began {
let vel = velocity(in: view)
if abs(vel.x) > abs(vel.y) {
state = .cancelled
}
}
}
}
Now I will create a panGesture
object and add to the imageView
.
let pangest = PanDirectionGestureRecognizer(target: self, action: #selector(ViewController.panAction(panrecogniser:)))
imageViewButton.addGestureRecognizer(pangest)
We have to calculate the minHeight
and viewCenter
values.
viewCenter = self.view.frame.height / 2
minHeight = viewCenter - 60
Let’s run the app and see the amazing animation.
Find the complete code here — github. If you like my post and want to get future update, do click 👏👏👏, follow me on medium and here . Happy coding 💪 💻