Search code examples
iosswiftanimationuiviewanimationtransitionios-animations

UiView.animateWithDuration Not Animating Swift


I am trying to animate show/hide of search bar using below code (The search bar should come from left and expand to right within 1-2 seconds). However, it doesn't animate and searchBar is immediately shown no matter how much time I put. I noticed following:

  • Duration is not respected
  • Not even delay is respected
  • Animation is not happening. Component is immediately shown

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    //code to get selected value...
    //Hide the collection view and show search bar
    
    UIView.animateWithDuration(10.0,
        delay: 0.0,
        options: UIViewAnimationOptions.TransitionCrossDissolve,
        animations: {
            self.searchBar.hidden = false
            self.searchBar.frame = CGRectMake(0, 0, 300, 44) //This doesn't work either
        },
        completion: { (finished: Bool) in
            return true
        })
    }
    

I am using Xcode 7, iOS 8 and Swift 2.0. I have seen at other solution, but none of them works for me. Kindly help...

Update: It worked with below code. However, it used default animation option of UIViewAnimationOptionCurveEaseInOut and TransitionNone

UIView.animateWithDuration(0.7,
                animations: {
                    self.searchBar.alpha = 1.0
                    self.searchBarRect.origin.x = self.searchBarRect.origin.x + 200
                    self.searchBar.frame = self.searchBarRect
                },
                completion: { (finished: Bool) in
                    return true
            })

Solution

  • Before the animateWithDuration, set the XPosition to -200 and YPosition to -200.

    Like Daniel Suggested, you need to also change the alpha from something other than 1.0 in order to see it "fade in".

    Are you using autolayout? If you are, you may want to animate the constraints instead of the frame.

    Finally, are you sure you've wired up the search bar properly?

    Edit: PS, I would keep the duration to something like 3.0 or 5.0. 10.0 will take forever and may make you think that it isn't doing anything because of how long it takes. Make it 3.0 or 5.0 (max) just for testing and then decrease to where you want it.