|
// |
|
// NavigationBarOverlappingDemo2.swift |
|
// |
|
// Created by Duc DoBa on 9/8/15. |
|
// Copyright (c) 2015 Duc Doba. All rights reserved. |
|
// |
|
// This example is created to answer to the following StackOverflow question: |
|
// http://stackoverflow.com/questions/32446076/how-to-overlap-uinavigationbar-with-animation |
|
|
|
import UIKit |
|
|
|
class ViewController: UIViewController { |
|
// Simply put an UIImageView right under UINavigationBar to see the result |
|
@IBOutlet weak var imageView: UIImageView! |
|
var frameInSuperView: CGRect = CGRectZero |
|
var frameInWindow: CGRect = CGRectZero |
|
|
|
override func viewDidAppear(animated: Bool) { |
|
var longPress = UILongPressGestureRecognizer(target: self, action: Selector("longPress:")) |
|
imageView.addGestureRecognizer(longPress) |
|
imageView.userInteractionEnabled = true |
|
} |
|
|
|
func longPress(gesture:UILongPressGestureRecognizer) { |
|
if gesture.state == UIGestureRecognizerState.Began { |
|
println("user pressed on image") |
|
|
|
self.bringImageViewToWindow() |
|
|
|
let bounds = imageView.bounds |
|
UIView.animateWithDuration( |
|
0.5, |
|
delay: 0.0, |
|
usingSpringWithDamping: 0.4, |
|
initialSpringVelocity: 10, |
|
options: UIViewAnimationOptions.CurveEaseInOut, |
|
animations: { |
|
self.imageView.bounds = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: bounds.size.width + 50, height: bounds.size.height + 50) |
|
}, |
|
completion: nil) |
|
} |
|
else if gesture.state == UIGestureRecognizerState.Changed { |
|
gesture.state == UIGestureRecognizerState.Began |
|
} |
|
else { |
|
println("user release on image") |
|
|
|
let bounds = imageView.bounds |
|
UIView.animateWithDuration(0.2, animations: { |
|
self.imageView.frame = self.frameInWindow |
|
}, completion: { finished in |
|
if finished { |
|
self.bringImageViewBack() |
|
} |
|
}) |
|
} |
|
} |
|
|
|
// This method is to ensure that the imageView will appear exactly at the point you want in the key window |
|
func bringImageViewToWindow() { |
|
let window = UIApplication.sharedApplication().keyWindow! |
|
let origin = imageView.superview!.convertPoint(imageView.frame.origin, toView: window) |
|
|
|
frameInSuperView = imageView.frame |
|
frameInWindow = CGRect(origin: origin, size: frameInSuperView.size) |
|
imageView.frame = frameInWindow |
|
|
|
window.addSubview(imageView) |
|
} |
|
|
|
func bringImageViewBack() { |
|
view.addSubview(imageView) |
|
|
|
// Without this block, the imageView will `disappear` magically for some reasons :-) |
|
let delay = 0.01 * Double(NSEC_PER_SEC) |
|
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) |
|
dispatch_after(time, dispatch_get_main_queue(), { |
|
self.imageView.frame = self.frameInSuperView |
|
}) |
|
} |
|
} |
|
|