2015-09-17 30 views
0

我正在研究一個原型(我對目標C太綠了),它有一個隱藏或顯示tableview的按鈕。 tableview從下到上出現,當你按下該按鈕時,它將通過將其滑回底部來隱藏該tableview。該tableview是一個子視圖btw。目標C:UITableView隱藏動畫不工作

下面是這個事情,「顯示」動畫效果很好,但隱藏動畫沒有,它實際上將桌面視圖從頂部滑動到視圖中,這顯然有些事情我沒有得到正確的結果。這裏的代碼:

if(self.showLists){ 
    self.showLists = NO; 

    //This is the show animation which is working properly 

    [UIView beginAnimations:nil context:nil]; 
    [UIView setAnimationDuration:0.4]; 
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn]; 

    [self.tableView setFrame:CGRectMake(0, self.tableView.frame.origin.y, self.tableView.frame.size.width, 0-self.tableView.frame.size.height)]; 


    [UIView commitAnimations]; 

}else{ 

    self.showLists = YES; 

    //This is the hide animation, the one that's not working as intended 

    [UIView beginAnimations:nil context:nil]; 
    [UIView setAnimationDuration:0.4]; 
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn]; 

    [self.tableView setFrame:CGRectMake(0, self.tableView.frame.size.height, self.tableView.frame.size.width, 0)]; 


    [UIView commitAnimations]; 

} 

我敢肯定,這是完全愚蠢的,但有時最小的細節是最糟糕的。據我所知,CGRectMake的第二個參數是我希望tableview在動畫完成時的位置,0代表頂部,而tableview的高度(比如500)代表右下角?

謝謝大家!

+0

您是否使用自動佈局設置tableview? – Istvan

+0

是的,你認爲這是造成衝突? –

回答

0

如果您使用自動佈局設置視圖,則不應更改其框架。你應該動畫它的約束。在這種情況下,如果它被設置,你可以動畫它的centerX和centerY約束。使用UIView animateWithDuration方法也更容易。

動畫到中間,假設centerX和centerY是tableview的水平和垂直中心NSLayoutConstraint。

centerX.constant = 0; 
centerY.constant = 0; 
[UIView animateWithDuration:0.4 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{ 
      [self.view layoutIfNeeded];  
      } completion:nil]; 
+0

很好的回答!但我還有一個問題,如果我使用這個修改頂端約束和設置tableview的高度,說topConstraint.constant = 600;由此產生的效果是,tableview不再可見,但沒有執行動畫,我玩了持續時間,但即使我設置了一秒,效果也是一樣的,也許我錯過了什麼? –

+0

Sry問題出在我的代碼中,你應該改變動畫塊外部的常量,並在動畫塊內的視圖上調用佈局(如果需要的話)。我已經更新了我的回答, – Istvan

+0

真棒,現在工作很好,並且感謝Autolayout的觀察,這是我不可能在不久的將來自己找到的方法! –

1

更簡單的方法是使用transform來修改tableView圖層。當使用變換時,我們不必更新框架,我們只需設置新的位置(翻譯)!

CGFloat tableViewHeight = CGRectGetHeight(self.tableView.frame); 
[UIView animateWithDuration:0.4 
       animations:^{ 
        // set the transform to animate to 
        self.tableView.layer.transform = CATransform3DMakeTranslation(0, tableViewHeight, 0); 
       } completion:^(BOOL finished) { 
        // when animation is finished, reset the transform 
        // if you also want to hide the tableView, here 
        // would be a good way to put it 
        self.tableView.layer.transform = CATransform3DIdentity; 
       }]; 
+0

優秀的答案呢!我希望我能接受不止一個答案,但我認爲Autolayout問題很重要。你的回答也很好,接下來我要做的就是在完成時改變tableview的alpha值,以便在你指出的時候保持隱藏,否則它會彈出回到原點,但是動畫就是我一直在尋找的東西,謝謝! –

-1

嘗試這行代碼中的

self.tableView.translatesAutoresizingMaskIntoConstraints = YES; 

希望它能幫助。