Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animating the width of UISearchBar frame

Is it possible to animate the frame width of a UISearchBar? I find when I apply uiview animations to widen the bounds of a search bar it pops immediately to the final result as if the object internally is assuming control of how it animates and not allowing me to apply my own animations to it smoothly.

If I animate the position it moves smoothly, but I suspect the fact that the text input adjusts according to the presence of the cancel button might mean we don't have public access to animate the width through UIView animation. The sample snippet below slides the bar from x = 0 to 100 but pops the width to 600 pixels wide.

CGRect searchBarFrame = self.searchViewController.searchBar.frame;
searchBarFrame.origin.x = 100;
searchBarFrame.size.width = 600;
[UIView animateWithDuration:1.0 
                      delay:0.0 
                    options:0 
                 animations:^{
                     self.searchViewController.searchBar.frame = searchBarFrame;
                 }
                 completion:^(BOOL completion){
                 }];
like image 417
Joey Avatar asked Mar 05 '12 18:03

Joey


2 Answers

there is an "issue" with UISearchBar due to the inner views forcing the resize to ignore the animation. However, this can be overcome by the use of - layoutSubviews. I have included the expand and contract code in my project below

[UIView animateWithDuration:.3
                 animations:^ {
                     CGRect newBounds = locationSearch.frame;
                     newBounds.size.width += 215; //newBounds.size.width -= 215; to contract
                     locationSearch.frame = newBounds;
                     [locationSearch layoutSubviews];
                 }];

Hope this helps.

like image 137
Stephen Hughes Avatar answered Nov 14 '22 22:11

Stephen Hughes


FYI, you can use UIViewAnimationOption instead of calling layoutsubviews explicitly, So the code would look something like this..

[UIView animateWithDuration:0.5
                              delay:0
                            options:UIViewAnimationOptionLayoutSubviews
                         animations:^{
                             //Set the frame you want to the search bar
                         }
                         completion:^(BOOL finished) {

                         }];
like image 15
akshaynhegde Avatar answered Nov 14 '22 22:11

akshaynhegde