[SWIFT] Create stretchy header with blur effect in ScrollView

Tram Ho

Development environment:

  • Swift Language Version: Swift 5
  • Xcode: Version 10.3
  • Deployment Target: 12.0

Step 1: Create the ViewController screen

We will create the ViewController screen as shown below:

Including the following components:

  • ScrollView: Add top, leading, trailing and bottom constraint, especially top set constraint with Superview (constant = 0).
  • View1: Add top, leading, trailing and bottom constraint with scrollView (constant = 0), with height = 1000 and width = View.width
  • Image1: Add top, leading, trailing constraint with View1 and height = 300; ContentMode = Aspect Fill.

Step 2: Create a stretchy header effect

We declare outlets, variables and initial values:

The value of imageHeightConstraint varies based on the offset value.

Inside:

  • originalHeight is the initial value of the image height constraint.
  • offset is the relative y coordinate value between the beginning of the viewport (contentView) and the beginning of the scrollView.
  • defaultTop is the initial value of the image top constraint.
  • currentTop is the current value of the image top constraint.

Step 3: Create a Blur Effect

We create the blurEffectView subview and set the constraint with imageView .

Inside:

  • UIVisualEffectView: object implements some complex effects.
  • UIViewPropertyAnimator: object allows creating effects on the change of views.
  • fractionComplete: The percentage of completion of the animation will change based on the offset value.

And this is the result:

References:

https://www.youtube.com/watch?v=R5CC1_QhrvY&list=PL0dzCUj1L5JGr7DuK-FxyIoabvP2ge5uY

Link github:

https://github.com/ndhuy96/SwiftTips/tree/stretchyHeader

Share the news now

Source : Viblo