UICollectionView show hide animation issue - ios

I am getting animation issue while hiding the UICollectionView. Show animation works fine but when I do the hide animation, it immediately hides the collection view without animation. This is the code :
#objc func openMenu(sender: UIButton) {
if sender.tag == 1 {
self.buttonView.tag = 2
self.arrow.image = UIImage(named: "arrowUp.png")
UIView.animate(withDuration: 0.7, animations: {
self.moduleView.frame.size.height = UIScreen.main.bounds.size.height - self.frame.size.height
}, completion: { _ in
})
} else {
self.buttonView.tag = 1
self.arrow.image = UIImage(named: "arrowDown.png")
UIView.animate(withDuration: 0.7, animations: {
self.moduleView.frame.size.height = 0
}, completion: { _ in
})
}
}
Output :
The strange thing is, I replaced the collection view with a simple UIView and it works fine. Bottom to top animation works perfectly. Code :
#objc func openMenu(sender: UIButton) {
if sender.tag == 1 {
self.buttonView.tag = 2
self.arrow.image = UIImage(named: "arrowUp.png")
UIView.animate(withDuration: 0.7, animations: {
self.testView.frame.size.height = UIScreen.main.bounds.size.height - self.frame.size.height
}, completion: { _ in
})
} else {
self.buttonView.tag = 1
self.arrow.image = UIImage(named: "arrowDown.png")
UIView.animate(withDuration: 0.7, animations: {
self.testView.frame.size.height = 0
}, completion: { _ in
})
}
}
Output :
Question : Why doesn't that work for UICollectionView ?
Initialisation :
UICollectionView :
self.moduleView = ModulesCollectionView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 0), collectionViewLayout: UICollectionViewLayout())
self.parentView.addSubView(self.moduleView)
UIView :
self.testView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 0))
self.parentView.addSubView(self.testView)

You need to use layoutSubViews() method for proper animation. Please change your code as below :
#objc func openMenu(sender: UIButton) {
if sender.tag == 1 {
self.buttonView.tag = 2
self.arrow.image = UIImage(named: "arrowUp.png")
UIView.animate(withDuration: 0.7, animations: {
self.moduleView.frame.size.height = UIScreen.main.bounds.size.height - self.frame.size.height
// Add this line
self.moduleView.layoutSubviews()
}, completion: { _ in
})
} else {
self.buttonView.tag = 1
self.arrow.image = UIImage(named: "arrowDown.png")
UIView.animate(withDuration: 0.7, animations: {
self.moduleView.frame.size.height = 0
// Add this line
self.moduleView.layoutSubviews()
}, completion: { _ in
})
}
}

Related

Move scrollview automatically with page controller

Hi I am using the PageController in my application.
I have inserted all the data on scrollView.
What I want do is, I want to move the scrollview automatically like page control with specific time.
When the scrollView reaches to last page it again recall all pages speedy and start from first onwards.
I want to load/get first page very smoothly after last page completion.
Find my code with following.
var slides:[Slide] = [];
var offSet: CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
slides = createSlides()
setupSlideScrollView(slides: slides)
pageControl.numberOfPages = slides.count
pageControl.currentPage = 0
view.bringSubview(toFront: pageControl)
let timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(autoScroll), userInfo: nil, repeats: true)
}
#objc func autoScroll() {
let totalPossibleOffset = CGFloat(slides.count - 1) * self.view.bounds.size.width
if offSet == totalPossibleOffset {
offSet = 0 // come back to the first image after the last image
}
else {
offSet += self.view.bounds.size.width
}
DispatchQueue.main.async() {
UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: {
self.scrollView.contentOffset.x = CGFloat(self.offSet)
}, completion: nil)
}
}
#objc func autoScroll() {
let totalPossibleOffset = CGFloat(slides.count - 1) * self.view.bounds.size.width
if offSet == totalPossibleOffset {
offSet = 0 // come back to the first image after the last image
}
else {
offSet += self.view.bounds.size.width
}
DispatchQueue.main.async() {
UIView.animate(withDuration: 0.1, delay: 0, options: UIView.AnimationOptions.curveLinear, animations: {
self.scrollView.scroll(topOffset:offSet, animated: true)
}, completion: nil)
}
}
extension UIScrollView {
// Bonus: Scroll
func scroll(topOffset:Float, animated: Bool) {
let ofSetValue = CGPoint(x: topOffset, y: 0)
setContentOffset(ofSetValue, animated: animated)
}
}
Use the following code working fine.
#objc func autoScroll() {
let totalPossibleOffset = CGFloat(slides.count - 1) * self.view.bounds.size.width
if offSet == totalPossibleOffset {
offSet = 0 // come back to the first image after the last image
}
else {
offSet += self.view.bounds.size.width
}
DispatchQueue.main.async() {
UIView.animate(withDuration: 0.0, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: {
self.scrollView.contentOffset.x = CGFloat(self.offSet)
}, completion: nil)
}
}

Animate (Rotate) UIBarButtonItem custom buttons

All I want to do is rotating the UIBarButtonItem when it is clicked.
I followed this post Rotate UIBarButtonItem Swift, but it is not working.
The difference is:
1- I set the image on runtime when view is loaded:
showHideBtn.image = showHeaderimage
2- I have two buttons in my right Bar button items:
Here is my code:
#IBAction func rotateAction(_ sender: Any) {
if(!self.isVertical)
{
UIView.animate(withDuration: 0.2, animations: {
self.navigationItem.rightBarButtonItem?.customView?.transform = CGAffineTransform(rotationAngle: 90 * .pi / 180)
}, completion: { (finished) in
self.isVertical = true
})
}else{
UIView.animate(withDuration: 0.2, animations: {
self.navigationItem.rightBarButtonItem?.customView?.transform = CGAffineTransform.identity
}, completion: { (finished) in
self.isVertical = false
})
}
}
What am I doing wrong?
Updated code:
DispatchQueue.main.async {
if(!self.isVertical) {
UIView.animate(withDuration: 0.2, animations: {
self.navigationItem.rightBarButtonItem?.customView?.transform = CGAffineTransform(rotationAngle: 90 * .pi / 180)
}, completion: { (finished) in
self.isVertical = true
})
}else {
UIView.animate(withDuration: 0.2, animations: {
self.navigationItem.rightBarButtonItem?.customView?.transform = CGAffineTransform(rotationAngle: 90 * .pi / 180)
}, completion: { (finished) in
self.isVertical = false
})
} }
Show button property:
It could be how you've set the custom view in the bar item. Maybe this self.navigationItem.rightBarButtonItem?.customView?. is returning nil. Anyway, here is a working version:
Creating the custom UIBarButtonItem:
let button1: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 30))
let button2: UIButton = UIButton(frame: CGRect(x: 70, y: 0, width: 60, height: 30))
override func viewDidLoad(_ animated: Bool) {
super.viewDidLoad(animated)
button1.backgroundColor = .gray
button1.setTitle("CustomButton", for: .normal)
button1.addTarget(self, action: #selector(rotateAction(_:)), for: .touchUpInside)
let barItem1: UIBarButtonItem = UIBarButtonItem(customView: button1)
button2.backgroundColor = .gray
button2.setTitle("CustomButton", for: .normal)
button2.addTarget(self, action: #selector(rotateAction(_:)), for: .touchUpInside)
let barItem2: UIBarButtonItem = UIBarButtonItem(customView: button1)
navigationItem.setRightBarButtonItems([barItem1, barItem2], animated: true)
}
Animate the tapped button:
#objc func rotateAction(_ sender: UIButton) {
let customView = sender
let transform: CGAffineTransform = isVertical ? .identity : CGAffineTransform(rotationAngle: 90 * .pi / 180)
UIView.animate(withDuration: 0.2, animations: {
customView.transform = transform
}, completion: { (finished) in
self.isVertical = !self.isVertical
})
}
To avoid replacing the bar button item/items set from storyboard, get those button items and create an array of bar button item including those with the ones you created in code:
let existingBarItems: [UIBarButtonItem] = navigationItem.rightBarButtonItems ?? []
let rightBarItems = existingBarItems = [yourCustomButtonItem]
navigationItem.setRightBarButtonItems(rightBarItems, animated: true)
And make sure your custom bar button item's frame doesn't intersect with existing buttons.

My pan gesture recognizer is very slow and unresponsive

I have a pan gesture recognizer in my app that does a function when swiped down. The animation used to be smooth but all of a sudden (without adding an code to that view controller) it becomes very laggy and I have to swipe down quickly for it to do that animation, It doesn't follow my finger.
What is the cause of that
class PhotoViewController: UIViewController, CLLocationManagerDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
override var prefersStatusBarHidden: Bool {
return true
}
private var backgroundImage: UIImage
private var backgroundImageView: UIImageView?
private var picker: UIPickerView
var list: [String]
var locationPicked: String
var locationArray: [Any]
var partyIndex: Int = Int()
init(image: UIImage) {
self.backgroundImage = image
self.picker = UIPickerView()
self.list = ["Loading..."]
self.locationPicked = list[0]
self.locationArray = []
super.init(nibName: nil, bundle: nil)
print(image)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/************************************/
override func viewDidLoad() {
super.viewDidLoad()
if Reachability.isConnectedToNetwork() == true{
mapApi()
}
let backgroundImageView = UIImageView(frame: view.frame)
backgroundImageView.image = backgroundImage
backgroundImageView.isUserInteractionEnabled = true
self.backgroundImageView = backgroundImageView
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(panGestureRecognizerAction(_:)))
backgroundImageView.addGestureRecognizer(panGestureRecognizer)
let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(longTap(sender:)))
backgroundImageView.addGestureRecognizer(longGesture)
view.addSubview(backgroundImageView)
view.backgroundColor = greenColor
picker.dataSource = self
picker.delegate = self
picker.frame = CGRect(x: ((self.view.frame.width)/2)-84, y: (self.view.frame.height)-70, width: 160, height: 40)
picker.clipsToBounds = true
picker.layer.cornerRadius = picker.bounds.size.width/20
picker.layer.borderColor = redColor.cgColor
picker.layer.borderWidth = 0
picker.backgroundColor = UIColor(colorLiteralRed: 217/255, green: 83/255, blue: 79/255, alpha: 0.85)
backgroundImageView.addSubview(picker)
print(list)
}
func panGestureRecognizerAction(_ gesture: UIPanGestureRecognizer){
let translation = gesture.translation(in: view)
if let bgImage = gesture.view{
if list.count > 1{
bgImage.frame.origin.y = translation.y
}
}
if gesture.state == .ended{
let tickName = "Tick.png"
let tickImage = UIImage(named: tickName)
let tick = UIImageView(image: tickImage!)
tick.frame = CGRect(x: ((self.view.frame.width)/2)-25, y: 150, width: 70, height: 70)
self.view.addSubview(tick)
tick.alpha = 0
let crossName = "Cross.png"
let crossImage = UIImage(named: crossName)
let cross = UIImageView(image: crossImage!)
cross.frame = CGRect(x: ((self.view.frame.width)/2)-25, y: (self.view.frame.height)-75, width: 50, height: 50)
self.view.addSubview(cross)
cross.alpha = 0
let velocity = gesture.velocity(in: view)
if (gesture.view?.frame.origin.y)! > CGFloat(100) || velocity.y > 1500 {
UIView.animate(withDuration: 0.4, animations: {
self.view.backgroundColor = greenColor
gesture.view?.frame.origin = CGPoint(x: 0, y: 275)
tick.alpha = 1
}, completion: { (true) in
UIView.animate(withDuration: 0.4, delay: 0.2, animations: {
tick.alpha = 0
})
if partyAt != nil{
self.uploadPartyPost()
} else{
self.uploadPost()
}
})
UIView.animate(withDuration: 0.5, delay: 1, animations: {
gesture.view?.frame.origin = CGPoint(x: 0, y: 0)
}, completion: { (true) in
self.dismiss(animated: true, completion: nil)
})
//send image here tick
} else if (gesture.view?.frame.origin.y)! < CGFloat(-80) || velocity.y > 1500 {
UIView.animate(withDuration: 0.2, animations: {
self.view.backgroundColor = redColor
gesture.view?.frame.origin = CGPoint(x: 0, y: -150)
cross.alpha = 1
}, completion: { (true) in
UIView.animate(withDuration: 0.5, delay: 0.7, animations: {
cross.alpha = 0
})
})
UIView.animate(withDuration: 0.2, delay: 1, animations: {
gesture.view?.frame.origin = CGPoint(x: 0, y: 0)
}, completion: { (true) in
self.dismiss(animated: true, completion: nil)
})
print("Done")
//send image here cross
} else {
UIView.animate(withDuration: 0.3, animations: {
gesture.view?.frame.origin = CGPoint(x: 0, y: 0)
})
}
}
}
After playing with translation of Pan gesture you need to set translation point back to zero.

Rotate UIBarButtonItem Swift

In Swift, I have a hamburger bar button, so when tapped I want that hamburger Bar button to rotate 90 degrees (so that the lines are vertical) and then when you click it again I would like it to go back to it's original state (horizontal)
NOTE: Can you make sure that this works for a UIBarButtonItem, because some solution to a normal UIButton does not work.
I use a UIButton inside of UIBarButtonItem to achieve this, and a variable with state vertical or not
this is my storyboard setup
Here is the code of simple view controller
import UIKit
class ViewController: UIViewController {
var isVertical : Bool = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func rotateAction(_ sender: Any) {
if(!self.isVertical)
{
UIView.animate(withDuration: 0.2, animations: {
self.navigationItem.leftBarButtonItem?.customView?.transform = CGAffineTransform(rotationAngle: 90 * .pi / 180)
}, completion: { (finished) in
self.isVertical = true
})
}else{
UIView.animate(withDuration: 0.2, animations: {
self.navigationItem.leftBarButtonItem?.customView?.transform = CGAffineTransform.identity
}, completion: { (finished) in
self.isVertical = false
})
}
}
}
Result
Hope this helps
#IBAction func rotateAction1(_ sender: Any) {
if (!self.isVertical) {
UIView.animate(withDuration: 0.2, animations: {
self.navigationItem.leftBarButtonItem?.customView?.transform = CGAffineTransform(rotationAngle: 90 * .pi / 180)
}, completion: {
(finished) in
self.isVertical = true
})
revealViewController().revealToggle(true)
} else {
UIView.animate(withDuration: 0.2, animations: {
self.navigationItem.leftBarButtonItem?.customView?.transform = CGAffineTransform.identity
}, completion: {
(finished) in
self.isVertical = false
})
revealViewController().revealToggle(false)
}
}
Swift 4:
func rotateBarButton() {
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40)) // Create new button & set its frame
button.setImage(#imageLiteral(resourceName: "settings"), for: UIControlState()) // Assign an image
let lef = UIBarButtonItem(customView: button)
self.navigationItem.leftBarButtonItem = lef// Set as barButton's customView
// Gets you half way there //
UIView.animate(withDuration: 0.8, delay: 0.1, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.navigationItem.leftBarButtonItem?.customView?.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
}, completion: nil)
// Rotates all the way around //
UIView.animate(withDuration: 0.5, delay: 0.5, options: UIViewAnimationOptions.curveEaseIn, animations: {
self.navigationItem.leftBarButtonItem?.customView?.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI * 2))
}, completion: nil)
}

Swift UITabBarController hide with animation

I'm trying to add animation to my tabBarController when hidden. Im able to accomplish this effect with the navigationBarController by using self.navigationController?.isNavigationBarHidden = true. I'm able to hide the tabBar by using self.tabBarController?.tabBar.isHidden = true but i do not get the animation how can I do this thank you in advance.
You could change the tab bar's frame inside an animation, so something like:
func hideTabBar() {
var frame = self.tabBarController?.tabBar.frame
frame?.origin.y = self.view.frame.size.height + (frame?.size.height)!
UIView.animate(withDuration: 0.5, animations: {
self.tabBarController?.tabBar.frame = frame!
})
}
func showTabBar() {
var frame = self.tabBarController?.tabBar.frame
frame?.origin.y = self.view.frame.size.height - (frame?.size.height)!
UIView.animate(withDuration: 0.5, animations: {
self.tabBarController?.tabBar.frame = frame!
})
}
Which sets the tab bar just below the visible screen, so that it slides up/down from the bottom.
I've developed a util extension for UIViewController
Swift 4 compatible:
extension UIViewController {
func setTabBarHidden(_ hidden: Bool, animated: Bool = true, duration: TimeInterval = 0.3) {
if animated {
if let frame = self.tabBarController?.tabBar.frame {
let factor: CGFloat = hidden ? 1 : -1
let y = frame.origin.y + (frame.size.height * factor)
UIView.animate(withDuration: duration, animations: {
self.tabBarController?.tabBar.frame = CGRect(x: frame.origin.x, y: y, width: frame.width, height: frame.height)
})
return
}
}
self.tabBarController?.tabBar.isHidden = hidden
}
}
Improvement of the response of #Luca Davanzo. If the bar is already hidden, it will continue hiding it and moving it lower. Also get rid of the return, so the state of the tabbar.hidden changes when the animation happens.
So I added a check:
extension UIViewController {
func setTabBarHidden(_ hidden: Bool, animated: Bool = true, duration: TimeInterval = 0.5) {
if self.tabBarController?.tabBar.isHidden != hidden{
if animated {
//Show the tabbar before the animation in case it has to appear
if (self.tabBarController?.tabBar.isHidden)!{
self.tabBarController?.tabBar.isHidden = hidden
}
if let frame = self.tabBarController?.tabBar.frame {
let factor: CGFloat = hidden ? 1 : -1
let y = frame.origin.y + (frame.size.height * factor)
UIView.animate(withDuration: duration, animations: {
self.tabBarController?.tabBar.frame = CGRect(x: frame.origin.x, y: y, width: frame.width, height: frame.height)
}) { (bool) in
//hide the tabbar after the animation in case ti has to be hidden
if (!(self.tabBarController?.tabBar.isHidden)!){
self.tabBarController?.tabBar.isHidden = hidden
}
}
}
}
}
}
}
In case if you need to toggle it from hide to visible and vice versa:
func toggleTabbar() {
guard var frame = tabBarController?.tabBar.frame else { return }
let hidden = frame.origin.y == view.frame.size.height
frame.origin.y = hidden ? view.frame.size.height - frame.size.height : view.frame.size.height
UIView.animate(withDuration: 0.3) {
self.tabBarController?.tabBar.frame = frame
}
}
Swift 4 solution:
tabBarController?.tabBar.isHidden = true
UIView.transition(with: tabBarController!.view, duration: 0.35, options: .transitionCrossDissolve, animations: nil)
Here is a simple extension :
func setTabBar(hidden:Bool) {
guard let frame = self.tabBarController?.tabBar.frame else {return }
if hidden {
UIView.animate(withDuration: 0.3, animations: {
self.tabBarController?.tabBar.frame = CGRect(x: frame.origin.x, y: frame.origin.y + frame.height, width: frame.width, height: frame.height)
})
}else {
UIView.animate(withDuration: 0.3, animations: {
self.tabBarController?.tabBar.frame = UITabBarController().tabBar.frame
})
}
}
So I've been playing around for 3 days with this now, finding out that the one that worked for me in my code was Adriana's post from 14th Sept 2018. But I was not sure how to use the coding once copied into my Project. So, after much experimenting I found that the way I could use this func was to put the following into into the respective swipe actions.
setTabBarHidden(false)
setTabBarHidden(true)
My next step is to try to get the swipe actions working while using UIScrollView in the same UIView at the same time.
You have to add UIView transitionWithView class func
Swift 2
func hideTabBarWithAnimation() -> () {
UIView.transitionWithView(tableView, duration: 1.0, options: .TransitionCrossDissolve, animations: { () -> Void in
self.tabBarController?.tabBar.hidden = true
}, completion: nil)
}
Swift 3, 4, 5
func hideTabBarWithAnimation() -> () {
UIView.transition(with: tableView, duration: 1.0, options: .transitionCrossDissolve, animations: { () -> Void in
self.tabBarController?.tabBar.isHidden = true
}, completion: nil)
}

Resources