Swift — Creating a Dynamic Popover Card View
How to implement draggable popover views in your iOS application
Many system applications in iOS 12, such as Voice Memos, contain draggable popover views. These views allow users to expand or hide information in the foreground, whilst blurring information in the background. In iOS 12 there is no built-in framework to support these views, despite their common use in system applications. However, once implemented, these views are both easy to use and essential for a polished iOS application.
Setting up the View
To begin, create a new XIB view and UIViewController called CardViewController, this can be achieved by selecting “also create XIB file” when creating the new view controller. These will be used to set up the card view’s storyboard and code.
The CardViewController view size will need to be set to freeform so that it can be used resized as a standalone view without inheriting IOS device properties. The files owner class is also set to the CardViewController and the files owner view is connected to the UIView.
The view is set up with a HandleView that is connected to the ViewController and will be used to resize the view. Any other objects can be added to the view for the desired purpose. In our example, two boxes will be used to demonstrate the popover:
Setting up the Primary View Controller
In the main ViewController class, the card view is set up and an enum is used to switch between the states of the card view being collapsed and expanded. The next state of the card is determined in the nextState variable, this will be used to expand or collapse the card. Other properties and variables are set up including the CardViewController, UIVisualEffectsView and the UIViewPropertyAnimator array.
Next, the XIB view is set up in the main view controller, the starting and ending card heights are determined using the view's height. Subviews are added programmatically to the bottom of the view and the visual effect view is added.
Tap and pan gesture recognizers are added to the CardViewController’s handle area. The tap gesture functions by recognizing when the handle has been touched informing the card to animate if needed. The pan gesture recognizer detects the handle area being dragged and adjusts the card animation accordingly as a fraction of the expanded card size.
Setting up the Animation
The popover view uses the UIViewPropertyAnimator for dynamic animation. This works by using the pan gesture recognizer to determine how much of the popover is completed and turning it into a percentage so the animation can be updated depending on how much the popover has completed. By using a tap recognizer, the popover snaps into place when released. The animation uses a liner animation for the popover effect and a curved animation for rounding corners of the popover. The code used can be seen below or in the GitHub repository.