2011-11-19 68 views
0

我有一段代碼說明單擊一個按鈕時,下面的代碼向下移動。我想知道是否可以再次點擊按鈕時,下面的按鈕會移回原始位置。在代碼中移動UIButtons

.H

@interface ViewController : UIViewController { 

IBOutlet UIButton *button; 
} 

-(IBAction)buttonClicked:(id)sender; 
-(IBAction)buttonClicked1:(id)sender; 

@end 

.M

- (void)buttonClicked:(id)sender { 
CGRect frame = button.frame; 
frame.origin.x = 65; // new x coordinate 
frame.origin.y = 130; // new y coordinate 
button.frame = frame; 
} 

回答

1

可以使用BOOL跟蹤狀態和存儲startRect用於移動按鈕退回

。 h

@interface ViewController : UIViewController { 
BOOL buttonShifted; 
CGRect startRect; 
IBOutlet UIButton *button; 
} 

-(IBAction)buttonClicked:(id)sender; 
-(IBAction)buttonClicked1:(id)sender; 

@end 

.M

// make sure to set the original button frame when view loads 
// ie startRect = button.frame; 

- (void)buttonClicked:(id)sender { 
if (buttonShifted) { 
    button.frame = startRect; 
} else { 
    CGRect frame = button.frame; 
    frame.origin.x = 65; // new x coordinate 
    frame.origin.y = 130; // new y coordinate 
    button.frame = frame; 
} 
    buttonShifted = !buttonShifted; 
}