Horizontal scrolling with parallax background for ios - ios

I'm facing a challenge of creating an introduction view, something like the "Cleanio" app (https://itunes.apple.com/fr/app/cleanio-pressing-la-demande/id885856031?mt=8).
Here is how it looks like:
So, the background and the overlay are moving independently and not in the same speed.
Does anyone have a start point how to realize that?

Yep.
What you need is two UIScrollViews. These should both be subviews of the main view (not contained in each other.
The bottom one has your image in it and the top one has the content.
Call them imageScrollView and contentScrollView.
Become the delegate of contentScrollView.
The contents will look something like this...
contents: [---page 1---][---page 2---][---page 3---][---page 4---]
image: [------------the image------------]
screen: [---screen---]
Key is that image is smaller than all the pages and bigger than the screen.
The frames of the scrollviews are the same width as the screen. This diagram is just to show the content widths not the frame widths.
So, the screen stays where it is and the two scroll views move over it.
Now the parallax part...
- (CGFloat)maxOffsetForScrollView:(UIScrollView *)scrollView
{
CGFloat contentWidth = scrollView.contentSize.width;
CGFloat frameWidth = CGRectGetWidth(scrollView.frame);
return contentWidth - frameWidth;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
// this is the delegate method for the content scroll view.
// I'm only doing horizontal stuff here, you can do vertical too if you want
CGFloat maximumContentOffset = [self maximumOffsetForScrollView:self.contentScrollView];
CGFloat currentOffset = self.contentScrollView.contentOffset.x;
CGFloat percentageOffset = currentOffset/maximumContentOffset;
CGFloat maximumImageOffset = [self maximumContentOffsetForScrollView:self.imageScrollView];
CGFloat actualImageOffset = maximumImageOffset * percentageOffset;
[self.imageScrollView setContentOffset:CGPointMake(actualImageOffset, 0)];
}
This takes the percentage offset from the content view and offsets the image view by the same percentage offset.
The result is a parallax effect. You can make it faster or slower by changing the relative sizes of the image and the content. More pages (or smaller image) = slower parallax.

I had been struggling with this parallax effect for a little while. I wouldn't have done it without #Fogmeister instructions, though I still had to figure out a couple of things by myself.
Anyway, here is a Swift 2.0 version, (hopefully a bit more complete):
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
var backgroundScrollView: UIScrollView!
var contentScrollView: UIScrollView!
var imageView: UIImageView!
var contentView: UIView!
var maxContentOffset: CGFloat!
var maxBackgroundOffset: CGFloat!
var cvbw: CGFloat!
var page: Int = 1
override func viewDidLoad() {
super.viewDidLoad()
self.createBackground()
self.createContent()
}
func createBackground() {
self.imageView = UIImageView(image: UIImage(named: "ParalaxMaterial.jpg")) //ParalaxMaterial.jpg is of size: 2500 x 2668px
self.imageView.frame = CGRectMake(0, 0, ((self.view.bounds.height/2668) * 2500), self.view.bounds.height)
self.backgroundScrollView = UIScrollView(frame: view.bounds)
self.backgroundScrollView.backgroundColor = UIColor.redColor()
self.backgroundScrollView.contentSize = imageView.bounds.size
self.backgroundScrollView.addSubview(self.imageView)
self.view.addSubview(self.backgroundScrollView)
self.maxBackgroundOffset = self.maxOffsetForScrollView(self.backgroundScrollView)
}
func createContent() {
self.contentView = UIView(frame: CGRectMake(0, 0, (self.view.bounds.width * 3), self.view.bounds.height))
self.contentScrollView = UIScrollView(frame: view.bounds)
self.contentScrollView.backgroundColor = UIColor.clearColor()
self.contentScrollView.contentSize = self.contentView.bounds.size
self.contentScrollView.delegate = self
let firstButton = UIButton()
firstButton.frame = CGRectMake(((self.contentView.bounds.width / 6) - 150), 300, 300, 100)
firstButton.setTitle("START", forState: UIControlState.Normal)
firstButton.titleLabel?.font = UIFont(name: "Arial", size: 18)
firstButton.addTarget(self, action: "firstAction:", forControlEvents: UIControlEvents.TouchUpInside)
self.contentView.addSubview(firstButton)
let firstLabel = UILabel()
firstLabel.frame = CGRectMake(((self.contentView.bounds.width / 6) - 100), 0, 200, 200)
firstLabel.text = "#BrusselsLockDown"
firstLabel.textAlignment = NSTextAlignment.Center
self.contentView.addSubview(firstLabel)
let secondLabel = UILabel()
secondLabel.frame = CGRectMake(((self.contentView.bounds.width / 2) - 100), 0, 200, 200)
secondLabel.text = "#LolCats"
secondLabel.textAlignment = NSTextAlignment.Center
self.contentView.addSubview(secondLabel)
let thirdLabel = UILabel()
thirdLabel.frame = CGRectMake((((self.contentView.bounds.width / 6) * 5) - 100), 0, 200, 200)
thirdLabel.text = "#Final"
thirdLabel.textAlignment = NSTextAlignment.Center
self.contentView.addSubview(thirdLabel)
self.contentScrollView.addSubview(self.contentView)
self.view.addSubview(self.contentScrollView)
self.maxContentOffset = self.maxOffsetForScrollView(self.contentScrollView)
self.cvbw = self.contentView.bounds.width
}
func scrollViewWillBeginDecelerating(scrollView: UIScrollView) {
if self.page == 1 {
if scrollView.contentOffset.x > 0 {
scrollView.setContentOffset(CGPointMake((self.cvbw / 3), 0), animated: true)
}
} else if self.page == 2 {
if scrollView.contentOffset.x < (self.cvbw * 4/12) {
scrollView.setContentOffset(CGPointMake(0, 0), animated: true)
} else if scrollView.contentOffset.x > (self.cvbw * 4/12) {
scrollView.setContentOffset(CGPointMake(((self.cvbw / 3) * 2), 0), animated: true)
}
} else if self.page == 3 {
if scrollView.contentOffset.x < (self.cvbw * 8/12) {
scrollView.setContentOffset(CGPointMake((self.cvbw / 3), 0), animated: true)
}
} else {
print("self.page messed up")
}
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView == self.contentScrollView {
let percentageOffset: CGFloat = self.contentScrollView.contentOffset.x / self.maxContentOffset
let currentBackgroundOffsetPoint: CGPoint = CGPointMake(((self.maxBackgroundOffset * percentageOffset) + 50), 0) self.backgroundScrollView.setContentOffset(currentBackgroundOffsetPoint, animated: false)
}
if self.contentScrollView.contentOffset.x == 0 {
print("page 1")
self.page = 1
} else if self.contentScrollView.contentOffset.x == 320 {
print("page 2")
self.page = 2
} else if self.contentScrollView.contentOffset.x == 640 {
print("page 3")
self.page = 3
}
}
func maxOffsetForScrollView(scrollView: UIScrollView) -> CGFloat {
let contentWidth: CGFloat = scrollView.contentSize.width - 100
let frameWidth: CGFloat = CGRectGetWidth(scrollView.frame)
return contentWidth - frameWidth
}
func firstAction (sender: UIButton) {
print("firstAction")
self.contentScrollView.setContentOffset(CGPointMake((self.cvbw / 3), 0), animated: true)
}
}

Related

NavigationBar titleview image move to another image with animation while scrolling

Green Image Place to Orange image exact match (x, y, width, height)
I try to move navigation bar titleView image to another image (Orange Image) with animation while user scrolling table view and when scroll up and down the put image to original place.
Sample Code
override func viewDidLoad() {
imgViewSmall = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: 44, height: 44))
imgViewSmall.backgroundColor = .green
self.navigationItem.titleView = imgViewSmall
imgView.backgroundColor = .orange
animator.pauseAnimation()
animator.addAnimations {
var smallSize = self.imgViewSmall.frame
let bigSize = self.imgView.frame
smallSize.size.width = bigSize.width
smallSize.size.height = bigSize.height
self.imgViewSmall.center = bigImageCoordinate
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let minHeight:CGFloat = 0.0
let maxHeight:CGFloat = 170.0
factor = ((scrollView.contentOffset.y - minHeight)) / (maxHeight - minHeight)
// update the new position acquired
self.lastContentOffset = scrollView.contentOffset.y
if factor == 0 {
//animator.stopAnimation(false)
}
else if factor == 1 {
//animator.stopAnimation(false)
}
else {
//animator.startAnimation()
animator.fractionComplete = factor
}
self.navigationItem.titleView?.setNeedsDisplay()
print("factor \(factor ?? 0)")
}

UIScrollView Reusable Views

I would like to create a UIScrollView that cycles between 3 paging views infinitely while I change the subviews to hold different reusable view controllers giving the illusion of infinitely many screen while only allocating the resources for 3 screens at a time similar to a UICollectionView.
Below is an attempt I've made at implementing such a view based on this answer Infinite UIScrollView however my project has not been working as expected.
Ive been trying to use 3 views as the basis for infinite scrolling and many labels as the subviews to be added and removed as the user scrolls.
import UIKit
class ViewController: UIViewController, UIScrollViewDelegate {
var scrollView:UIScrollView = {
let scrollView:UIScrollView = UIScrollView()
scrollView.backgroundColor = UIColor.orange
scrollView.translatesAutoresizingMaskIntoConstraints = false
return scrollView
}()
var labels:[CustomLabel] = [CustomLabel]()
var pages:[Page] = [Page]()
var visiblePages:Set<Page>!{
didSet{
print("visible pages count: \(recycledPages.count)")
}
}
var recycledPages:Set<Page>!{
didSet{
print("recycled pages count: \(recycledPages.count)")
}
}
var visibleLabels:Set<CustomLabel>!
var recycledLabels:Set<CustomLabel>!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
recycledPages = Set<Page>()
visiblePages = Set<Page>()
recycledLabels = Set<CustomLabel>()
visibleLabels = Set<CustomLabel>()
scrollView.contentSize = CGSize(width: view.bounds.width * 3, height: view.bounds.height)
scrollView.delegate = self
scrollView.isPagingEnabled = true
scrollView.indicatorStyle = .white
view.addSubview(scrollView)
NSLayoutConstraint.activate([
scrollView.topAnchor.constraint(equalTo: view.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
configureLabels()
setUpPages()
for i in 0..<pages.count{
scrollView.addSubview(pages[i])
}
}
func setUpPages(){
let page1 = Page(),page2 = Page(),page3 = Page()
page1.backgroundColor = .red
page2.backgroundColor = .green
page3.backgroundColor = .blue
page1.index = 0
page2.index = 1
page3.index = 2
pages = [page1,page2,page3]
visiblePages = [page1,page2,page3]
setContentViewFrames()
}
func configureLabels(){
let label1 = CustomLabel(), label2 = CustomLabel(), label3 = CustomLabel()
label1.text = "label1"
label2.text = "label2"
label3.text = "label3"
label1.backgroundColor = .red
label2.backgroundColor = .green
label3.backgroundColor = .blue
labels = [label1,label2,label3]
setContentViewFrames()
}
// func dequeueRecycledPage()->CustomLabel?{
// let page = recycledPages.first
// if let page = page{
// recycledPages.remove(page)
// return page
// }
// return nil
// }
var currentIndex = 0
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (scrollView.contentOffset.x < 0) {
let newOffset = CGPoint(x: scrollView.bounds.width + scrollView.contentOffset.x, y: 0)
scrollView.contentOffset.x = newOffset.x
rotateViewsRight()
}else if(scrollView.contentOffset.x > scrollView.bounds.size.width*2){
let newOffset = CGPoint(x: scrollView.contentOffset.x - scrollView.bounds.width, y: 0)
scrollView.contentOffset.x = newOffset.x
rotateViewsLeft()
}
print("current index: \(currentIndex)")
}
lazy var previousOffset:CGPoint = CGPoint()
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
print("currentIndex called")
if previousOffset.x < scrollView.contentOffset.x{
currentIndex += 1
}else if previousOffset.x > scrollView.contentOffset.x{
currentIndex -= 1
}
previousOffset = scrollView.contentOffset
}
func rotateViewsRight(){
let endView = pages.removeLast()
pages.insert(endView, at: 0)
setContentViewFrames()
}
func rotateViewsLeft(){
let endView = pages.removeFirst()
pages.append(endView)
setContentViewFrames()
}
func setContentViewFrames(){
for i in 0..<pages.count{
// let adjustedIndex = i % pages.count
// let view = pages[i]
// view.frame = CGRect(origin: CGPoint(x: view.bounds.width * CGFloat(i), y: 0), size: view.bounds.size)
pages[i].frame = CGRect(x: CGFloat(i)*view.bounds.width, y: 0, width: view.bounds.width, height: view.bounds.height)
let label = labels[currentIndex%labels.count]
label.text = "current label: \(currentIndex)"
label.frame = pages[i].frame
pages[i].addSubview(label)
}
}
func configurePage(forIndex index:Int){
}
func dequeueRecycledPage()->Page?{
let page = recycledPages.first
if let page = page{
recycledPages.remove(page)
return page
}
return nil
}
}

UIScrollView scrolls out of image after image is zoomed in?

I'm trying to implement a image zooming functionality using UIScrollview. where as I kept image as aspect fit.
Image is inside a UIScrollView, and image frame has been given similar to UIScrollView.
Here is my code.
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
scroller.minimumZoomScale = 1.0
scroller.maximumZoomScale = 7.0
}
// MARK: - User Defined Methods
#IBAction func doubleTapGestureAction(_ sender: UITapGestureRecognizer)
{
if scroller.zoomScale == 1
{
scroller.zoom(to: zoomForScale(scale: scroller.maximumZoomScale, center: sender.location(in: sender.view)), animated: true)
}
else
{
scroller.setZoomScale(1, animated: true)
}
print(isZoomedIn)
}
func zoomForScale(scale: CGFloat, center: CGPoint) -> CGRect
{
var zoomRect = CGRect.zero
zoomRect.size.height = image.frame.size.height / scale
zoomRect.size.width = image.frame.size.width / scale
let newCenter = image.convert(center, from: scroller)
zoomRect.origin.x = newCenter.x - (zoomRect.size.width / 2.0)
zoomRect.origin.y = newCenter.y - (zoomRect.size.height / 2.0)
return zoomRect
}
func viewForZooming(in scrollView: UIScrollView) -> UIView?
{
return image
}
Here is sample code:
import UIKit
class ViewController: UIViewController,UIScrollViewDelegate {
var imgDemo: UIImageView = {
let img = UIImageView()
img.contentMode = .scaleAspectFill
img.isUserInteractionEnabled = true
return img
}()
var scrollView:UIScrollView = {
let scroll = UIScrollView()
scroll.maximumZoomScale = 4.0
scroll.minimumZoomScale = 0.25
scroll.clipsToBounds = true
return scroll
}()
override func viewDidLoad() {
super.viewDidLoad()
imgDemo.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)
imgDemo.image = UIImage(named: "5.jpg")
scrollView.delegate = self
scrollView.frame = imgDemo.frame
scrollView.addSubview(imgDemo)
view.addSubview(scrollView)
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imgDemo
}
}
Take a look at these methods. May be it will help. I have scroll view stretched to controller's view size. customizeScrollView() will calculate min and max scale options. centerImageView() will put UIImageView in the center of your UIScrollView
Call the customizeScrollView function in viewDidload.
fileprivate func customizeScrollView() {
guard let image = imageView?.image else { return }
var minZoom = fmin(self.view.frame.width / image.size.width, self.view.frame.height / image.size.height)
minZoom = fmin(1.0, minZoom)
scrollView?.contentSize = image.size
scrollView?.minimumZoomScale = minZoom
scrollView?.addSubview(self.imageView!)
scrollView?.setZoomScale(minZoom, animated: false)
centerImageView()
}
fileprivate func centerImageView() {
guard let imageView = imageView else { return }
guard let scrollView = scrollView else { return }
let boundsSize = scrollView.bounds.size
var frameToCenter = imageView.frame
// Center horizontally
if frameToCenter.size.width < boundsSize.width {
frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2
} else {
frameToCenter.origin.x = 0
}
// Center vertically
if frameToCenter.size.height < boundsSize.height {
frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2
} else {
frameToCenter.origin.y = 0
}
imageView.frame = frameToCenter
}
public func scrollViewDidZoom(scrollView: UIScrollView) {
print(imageView.frame)
centerImageView()
}

Zooming into an image from user's touch point with UIScrollView in Swift

The below Swift code manages zooming in and out of an UIImage inside a UIScrollView.
When double tapping, the image zooms into the centre and zooms out to the centre.
Question:
What code changes need to be made to set the zoom in point to be the centre of the image area the user touches on screen?
(For example, if the user double taps the top left of the image, the image would correspondingly zoom into the top left of the image.)
class ScrollViewController: UIViewController, UIScrollViewDelegate {
var scrollView: UIScrollView!
var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imageView = UIImageView(image: UIImage(named: "image.png"))
scrollView = UIScrollView(frame: view.bounds)
scrollView.backgroundColor = UIColor.blackColor()
scrollView.contentSize = imageView.bounds.size
scrollView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
scrollView.contentOffset = CGPoint(x: 1000, y: 450)
scrollView.addSubview(imageView)
view.addSubview(scrollView)
scrollView.delegate = self
setZoomScale()
setupGestureRecognizer()
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
override func viewWillLayoutSubviews() {
setZoomScale()
}
func setZoomScale() {
let imageViewSize = imageView.bounds.size
let scrollViewSize = scrollView.bounds.size
let widthScale = scrollViewSize.width / imageViewSize.width
let heightScale = scrollViewSize.height / imageViewSize.height
scrollView.minimumZoomScale = min(widthScale, heightScale)
scrollView.zoomScale = 1.0
}
func scrollViewDidZoom(scrollView: UIScrollView) {
let imageViewSize = imageView.frame.size
let scrollViewSize = scrollView.bounds.size
let verticalPadding = imageViewSize.height < scrollViewSize.height ? (scrollViewSize.height - imageViewSize.height) / 2 : 0
let horizontalPadding = imageViewSize.width < scrollViewSize.width ? (scrollViewSize.width - imageViewSize.width) / 2 : 0
scrollView.contentInset = UIEdgeInsets(top: verticalPadding, left: horizontalPadding, bottom: verticalPadding, right: horizontalPadding)
}
func setupGestureRecognizer() {
let doubleTap = UITapGestureRecognizer(target: self, action: "handleDoubleTap:")
doubleTap.numberOfTapsRequired = 2
scrollView.addGestureRecognizer(doubleTap)
}
func handleDoubleTap(recognizer: UITapGestureRecognizer) {
if (scrollView.zoomScale > scrollView.minimumZoomScale) {
scrollView.setZoomScale(scrollView.minimumZoomScale, animated: true)
} else {
scrollView.setZoomScale(scrollView.maximumZoomScale, animated: true)
}
}
}
According to this post. It works fine with me.
func handleDoubleTap(recognizer: UITapGestureRecognizer) {
if (scrollView.zoomScale > scrollView.minimumZoomScale) {
scrollView.setZoomScale(scrollView.minimumZoomScale, animated: true)
} else {
let touchPoint = recognizer.locationInView(view)
let scrollViewSize = scrollView.bounds.size
let width = scrollViewSize.width / scrollView.maximumZoomScale
let height = scrollViewSize.height / scrollView.maximumZoomScale
let x = touchPoint.x - (width/2.0)
let y = touchPoint.y - (height/2.0)
let rect = CGRectMake(x, y, width, height)
scrollView.zoomToRect(rect, animated: true)
}
}
Here's a Swift 2.3 function for returning the location of a touch inside a zoomable UIScrollView:
UIScrollView with UIImageView inside
Zoomed or not - scrollView.zoomScale
imageView.contentMode = .ScaleAspectFit
The image can be bigger, high res than imageView and scrollView
Any shape of the image, portrait, landscape or square
imageView.contentMode = .ScaleAspectFit
//import AVFoundation // needed for AVMakeRectWithAspectRatioInsideRect()
func getLocationOfTouchInImageInScrollView(paintLocation:CGPoint)->CGPoint {
let imageSize = imageViewInScrollView.image!.size
let imageFrame = scrollView.frame
let imageRect = AVMakeRectWithAspectRatioInsideRect(imageSize, imageFrame)
let imageHeightToViewHeight = max(imageSize.height, imageSize.width) / imageFrame.size.height
let px = (max(0, min(imageSize.width, ((paintLocation.x - imageRect.origin.x) * imageHeightToViewHeight))))
let py = (max(0, min(imageSize.height, ((paintLocation.y - imageRect.origin.y ) * imageHeightToViewHeight))))
var imageTouchPoint = CGPointMake(CGFloat(px), CGFloat(py))
return imageTouchPoint
}
Took me DAYS to write this one since I couldn't figure out the imageHeightToViewHeight variable, thought there was something else funny going on.

Paging UIScrollView seems to place content off centre

I have a UIScrollView that I want to have paging functionality (think an initial splash screen). I want that content (a UILabel and a UIImageView) to be placed centrally in each paging view on the scrollView. My problem is is that it is always slightly off centre ().
Here is the complete code:
var splashScreenObjects = [SplashScreenObject]()
var imageViewArray = [UIImageView]()
var subtitleViewArray = [UILabel]()
#IBOutlet var scrollView: UIScrollView!
#IBOutlet var pageControl: UIPageControl!
override func viewDidLoad() {
super.viewDidLoad()
createSplashScreenObjects()
configurePageControl()
configureScrollView()
}
func createSplashScreenObjects() {
let firstScreen: SplashScreenObject = SplashScreenObject(subtitle: "Medication reminders on your phone. Never miss your next dose", image: UIImage(named: "splashScreen1")!)
let secondScreen: SplashScreenObject = SplashScreenObject(subtitle: "Track how good you have been with your medication", image: UIImage(named: "splashScreen2")!)
let thirdScreen: SplashScreenObject = SplashScreenObject(subtitle: "The better you are with your medication, the more points you'll earn!", image: UIImage(named: "splashScreen3")!)
splashScreenObjects.append(firstScreen)
splashScreenObjects.append(secondScreen)
splashScreenObjects.append(thirdScreen)
}
func configureScrollView() {
self.scrollView.layoutIfNeeded()
self.scrollView.showsHorizontalScrollIndicator = false
self.scrollView.showsVerticalScrollIndicator = false
self.scrollView.pagingEnabled = true
self.scrollView.delegate = self
let width = view.frame.size.width
for index in 0..<splashScreenObjects.count {
let subtitle = UILabel(frame: CGRectMake((width * CGFloat(index)) + 25, self.scrollView.frame.size.height-75, width-50, 75))
subtitle.text = splashScreenObjects[index].subtitle
subtitle.textAlignment = NSTextAlignment.Center
subtitle.textColor = UIColor.whiteColor()
subtitle.font = UIFont(name:"Ubuntu", size: 16)
subtitle.numberOfLines = 2
subtitle.backgroundColor = UIColor.clearColor()
self.scrollView.addSubview(subtitle)
self.subtitleViewArray.append(subtitle)
subtitle.alpha = 0
let mainImage = UIImageView(frame: CGRectMake((width * CGFloat(index)), 50, width, self.scrollView.frame.size.height-150))
mainImage.image = splashScreenObjects[index].image
mainImage.contentMode = UIViewContentMode.ScaleAspectFit
self.scrollView.addSubview(mainImage)
self.imageViewArray.append(mainImage)
mainImage.alpha = 0
}
self.scrollView.contentSize = CGSizeMake(width * CGFloat(splashScreenObjects.count), self.scrollView.frame.size.height-50)
animateViews(Int(0))
}
func configurePageControl() {
self.pageControl.numberOfPages = splashScreenObjects.count
self.pageControl.currentPage = 0
self.view.addSubview(pageControl)
pageControl.addTarget(self, action: #selector(SplashViewController.changePage(_:)), forControlEvents: UIControlEvents.ValueChanged)
}
func changePage(sender: AnyObject) -> () {
let x = CGFloat(pageControl.currentPage) * self.view.frame.size.width
scrollView.setContentOffset(CGPointMake(x, 0), animated: true)
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
let pageNumber = round(scrollView.contentOffset.x / self.view.frame.size.width)
pageControl.currentPage = Int(pageNumber)
animateViews(Int(pageNumber))
}
func animateViews(pageNumber: Int) {
UIView.animateWithDuration(0.5, animations: {
self.imageViewArray[pageNumber].alpha = 1.0
self.subtitleViewArray[pageNumber].alpha = 1.0
})
}
Here are my auto layout constraints for the UIScrollView:
Your leading and trailing spaces are both -20, which means that the scroll view is 40 points wider than its superview. Change these to 0.
You should replace
self.scrollView.layoutIfNeeded()
to
self.view.layoutIfNeeded()
because layoutIfNeeded layout caller subviews, not itself. So, scrollView, when you add subtitle and mainImage on it, has wrong frame.

Resources