2014-02-27 64 views
0

我有這麼多代碼的遊戲,但它的大部分是一遍又一遍地重複相同的空白只有一個按鈕的差異。如何在一個按鈕的地方做一個變量?

我簡化了代碼用於此目的:

-(void)button1Action { 
    if (CGRectIntersectsRect(button1.frame, image1.frame)) { 
     //button 1 is used a few times between these two brackets 
    } 
} 
-(void)button2Action { 
    if (CGRectIntersectsRect(button2.frame, image1.frame)) { 
     //button 2 is used a few times between these two brackets 
    } 
} 
-(void)button3Action { 
    if (CGRectIntersectsRect(button3.frame, image1.frame)) { 
     //button 3 is used a few times between these two brackets 
    } 
} 

有我做一個空隙用這樣的一種方式?:

-(void)buttonXAction { 
    if (CGRectIntersectsRect(buttonX.frame, image1.frame)) { 
     //button X is used a few times between these two brackets 
    } 
} 

謝謝!

回答

0

創建一個方法是這樣的:

- (void)buttonAction:(UIButton *)sender { 

     if (CGRectIntersectsRect(sender.frame, image1.frame)) { 

     //This will perform the action on what ever buttons calls the method. 
} 

希望這有助於!

+0

我想這是我需要的東西!但是,在這種情況下如何聲明發件人是什麼? – Vince

+0

您可以將操作添加到每個按鈕,如下所示:[button1 addTarget:self action:@selector(buttonAction:)forControlEvents:UIControlEventTouchUpInside]; – DominicanCoder

+0

爲每個按鈕做這件事,他們將成爲「發件人」的論據。這將執行調用該方法的每個按鈕的代碼。 – DominicanCoder

相關問題