2010-09-30 247 views
0

我有以下代碼的UIView的animateWithDuration:動畫:完成:錯誤

-(void) animate:(UIButton*) b withState: (int) state andLastState:(int) last_state { 
if (state < last_state) { 
    int stateTemp = state; 
    float duration = 1.0/30.0; 
    [b animateWithDuration: duration 
     animations: ^{ [UIImage imageNamed:[NSString stringWithFormat:@"m1.a000%d.png", state]]; } 
    completion: ^{ animate(b, stateTemp++, last_state); }]; 
    } 
} 

,但得到的錯誤增量只讀變量stateTemp

我試圖通過設置動畫的一系列圖像UIButton s圖像。

這段代碼有什麼問題?

回答

4

塊內使用的任何變量是const複製。所以真的你所做的是這樣的:

-(void) animate:(UIButton*) b withState: (int) state andLastState:(int) last_state { 
if (state < last_state) { 
int stateTemp = state; 
float duration = 1.0/30.0; 
[b animateWithDuration: duration 
    animations: ^{ 
     [UIImage imageNamed:[NSString stringWithFormat:@"m1.a000%d.png", state]]; 
    } 
    completion: ^{ 
     const int stateTempCopy = stateTemp; 
     animate(b, stateTempCopy++, last_state); 
    } 
]; 
} 
} 

問題是試圖改變const變量。你不能那樣做。幸運的是,有一種解決方法,那就是__block說明符。

只需將int stateTemp = state;更改爲__block int stateTemp = state;,您就可以輕鬆前往。 (有關__block的文件,請查看the documentation

相關問題