NavigationBar titleview image move to another image with animation while scrolling - ios

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)")
}

Related

Image Zoom not working in a UIScrollView inside a Root UIScrollView

I'm trying to zoom an image that is inside a UIScrollView, and that UIScrollView it's inside of a root UIScrollView that allow paging, similar to the Photos app.
In the viewDidLoad() inside the view that contains the root scrollView I call prepareScrollView()
func prepareScrollView(){
let tap = UITapGestureRecognizer(target: self, action: #selector(hideNavigationItem))
scrollView.addGestureRecognizer(tap)
scrollView.delegate = self
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 4.0
scrollView.zoomScale = 1.0
let width = self.view.bounds.width
let height = self.view.bounds.height
totalWidth = width * CGFloat((imageArray!.count)!) //The width must be the width of the screen by the number of the images in the array
scrollView.contentSize = CGSize(width: totalWidth, height: height)
scrollView.isPagingEnabled = true
loadPages()
}
The loadPages() function load every scrollView with their image and add it to the root scrollview.
func loadPages(){
for i in 0...((imageArray!.count)! - 1){
let pageScroll = Page(frame: CGRect(x: self.view.bounds.size.width * CGFloat(i), y: self.view.frame.origin.y, width: self.view.bounds.size.width, height: self.view.bounds.size.height))
pageScroll.minimumZoomScale = 1.0
pageScroll.maximumZoomScale = 4.0
pageScroll.zoomScale = 1.0
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height))
imageView.image = UIImage(data: (imageArray![i])!)
imageView.contentMode = .scaleToFill
pageScroll.addSubview(imageView)
scrollView.addSubview(pageScroll)
}
}
The Page object it's just a UIScrollView object.
class Page: UIScrollView {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.subviews[0]//Return the image
}
}
And inside the root scrollView viewForZooming function it calls the viewForZooming function of the correspond child scrollview.
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
if(self.scrollView.subviews.count > 0){
let childScrollView = self.scrollView.subviews[currentPage] as! Page
let image = childScrollView.viewForZooming(in: scrollView)
return image
}
return nil
}
With this approach I can navigate horizontally but I can't zoom in the current image. The viewForZooming function executes in both objects. What I'm doing wrong?
Finally I solve my issue. I changed the Page object to a simple UIScrollView and then set the delegate of the scrollView object to self.
func loadPages(){
for i in 0...((comic?.comicsPages!.count)! - 1){
let pageScroll = UIScrollView(frame: CGRect(x: self.view.bounds.size.width * CGFloat(i), y: self.view.frame.origin.y, width: self.view.bounds.size.width, height: self.view.bounds.size.height))
pageScroll.minimumZoomScale = 1.0
pageScroll.maximumZoomScale = 4.0
pageScroll.zoomScale = 1.0
pageScroll.isUserInteractionEnabled = true
pageScroll.delegate = self //Here
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: self.view.bounds.size.height))
imageView.image = UIImage(data: (imageArray![i])!)
imageView.contentMode = .scaleToFill
pageScroll.addSubview(imageView)
scrollView.addSubview(pageScroll)
}
}
And then in the viewForZooming function of the root scrollView I change the code for this:
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
if(scrollView.subviews.count > 0){
return scrollView.subviews[0]
}
return nil
}
The scrollView parameter is the child scrollview so it works as expected.

Scroll view Does not show images but scrolls?

I am trying to learn the basics of IOS development and Ive been experimenting with different views.
I tried to make a scroll view that display an array of images which scrolls properly but none of the images appear?
import UIKit
class ViewController: UIViewController {
var imagesArray = [UIImage]()
let scrollView: UIScrollView = {
let scroll = UIScrollView()
scroll.isPagingEnabled = true
scroll.showsVerticalScrollIndicator = false
scroll.showsHorizontalScrollIndicator = false
scroll.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
return scroll
}()
override func viewDidLoad() {
super.viewDidLoad()
setScrollView()
}
func setScrollView(){
self.view.addSubview(scrollView)
imagesArray = [UIImage(named:"gamerrr"),UIImage(named:"family"),UIImage(named:"gamerrr"),UIImage(named:"family"),UIImage(named:"family")] as! [UIImage]
setUpImages(imagesArray)
}
func setUpImages(_ images:[UIImage]){
for i in 0..<images.count {
// container of each image
let imageView = UIImageView()
// shifting to next image
let xPos = UIScreen.main.bounds.width * CGFloat(i)
// width and height of the screen
imageView.frame = CGRect(x: xPos, y: 0, width: scrollView.frame.width, height: scrollView.frame.height)
imageView.contentMode = .scaleAspectFit
// shifting to next image
scrollView.contentSize.width = scrollView.frame.width * CGFloat(i+1)
scrollView.addSubview(imageView)
}
}
}
You may need to set the image
let imageView = UIImageView(image:images[i])

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()
}

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.

Horizontal scrolling with parallax background for 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)
}
}

Resources