2014-07-02 77 views
0

我正在使用objective-c在iOS7中使用動畫。我想使用它具有以下定義animateWithDuration功能:UIView animateWithDuration動畫和完成參數的獨立函數

[UIView animateWithDuration:(NSTimeInterval) animations:^(void)animations completion:^(BOOL finished)completion] 

我可以用這個蠻好的,但它使我的代碼過長,因爲我已經把我的動畫和完成的功能都在這個聲明。我想創建一個單獨的函數並將其傳遞給動畫函數調用。

具體而言,我希望能夠有一個單獨的完成功能與多個動畫一起使用,這也需要能夠將它傳遞給特定視圖的ID的參數。

有人可以解釋如何設置一個可以傳遞給動畫函數的函數,以及^(void)和^(BOOL)中'^'是什麼意思?

感謝

+1

瞭解Objective-C的塊。 – rmaddy

+0

http://stackoverflow.com/questions/3499186/what-does-this-syntax-mean-in-objective-c塊是什麼意思。 – michaelsnowden

+0

作爲「rmaddy」已經提到,進入並學習塊編程。它是Objective-C編程的重要組成部分。 – BonanzaDriver

回答

0

^表示a block(請注意,這些都不是功能)。你當然可以做你想做的。你可以使用:

returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};

所以您的代碼會是這個樣子:

void (^animations)() = ^{ 
    // Do some animations. 
}; 

void (^completion)(BOOL) = ^(BOOL finished){ 
    // Complete. 
}; 

[UIView animateWithDuration:1 animations:animations completion:completion]; 

僅供參考,這是塊語法有很大的參考:http://goshdarnblocksyntax.com/

0

不要過於複雜的事情。只要使用此方法改爲:

[UIView animateWithDuration:1.0 animations:^{ 
    // your animations 
}]; 

下一次你遇到你有沒有用一擋,只是把nil塊中。

[UIView animateWithDuration:1.0 
        animations:^{ 
         // your animations 
        } 
        completion:nil]; 

^表示您正在Objective-C中聲明一個塊。

如果你只是想使你的方法調用短,你可以這樣做:

void (^myCompletionBlock)(BOOL finished) = ^void(BOOL finished) { 
    // What you want to do on completion 
}; 

[UIView animateWithDuration:1.0 
       animations:^{ 
        // your animations 
       } 
       completion:myCompletionBlock]; 
相關問題