如何用动画在x方向延长UISearchBar?

时间:2012-11-27 22:13:09

标签: ios core-animation uisearchbar

我想将右侧搜索栏向左延伸20 px,并使用动画向右缩短左侧搜索栏20 px。我怎么能这样做?

CGRect leftFrame = self.leftSearchBar.frame;
    //leftFrame.origin.x = leftFrame.origin.x - 20;
    leftFrame.size.width = leftFrame.size.width - 40;

    CGRect rightFrame = self.rightSearchBar.frame;
    rightFrame.origin.x = rightFrame.origin.x - 40;
    rightFrame.size.width = rightFrame.size.width + 40;

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelay:0.0];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];

    self.leftSearchBar.frame = leftFrame;
    self.rightSearchBar.frame = rightFrame;

    [UIView commitAnimations];

它不起作用。它首先在没有动画的情况下调整视图大小,然后使用动画移动右视图。

1 个答案:

答案 0 :(得分:1)

假设你没有改变锚点或类似的东西,只需扩展宽度就会使它向右伸展。在UIView动画块中包装它,它应该根据问题中的规范进行动画处理,如下所示:

UISearchBar* searchbar = ...; // However you've created your UISearchBar, we'll refer to it as 'searchbar'

CGRect searchFrame = searchbar.frame;
[UIView animateWithDuration:0.8 
                      delay:0.0
                    options:UIViewAnimationOptionBeginFromCurrentState
                 animations:^{
                     searchFrame.size.width += 30;
                     searchbar.frame = searchFrame;
                 }
                 completion:nil];

您需要确保+= 30不会被多次调用,否则每次调用会增加30点 。如果你事先知道尺寸,你可以简单地用= size + 30替换它,这是一个更安全的赌注,因为你不止一次调用动画。