在方法中保留变量

时间:2011-07-17 21:49:58

标签: objective-c ios animation uibutton cgpoint

这应该很容易。

我有一种方法可以上下移动视图,同时我会上下移动UIButton ...然后在方法再次运行时将按钮移回原来的位置。

我以为我可以使用float originalCenterX = topSubmitButton.center.x和float originalCenterY = topSubmitButton.center.y来获取按钮的原始位置,但是当方法被命中时,这些会被按钮的中心覆盖第二次。

如何在方法的多次迭代中保留变量?

-(IBAction)scrollForComment { 

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5]; 

CGRect rect = self.view.frame;

NSLog(@"button center x = %f y = %f",topSubmitButton.center.x,topSubmitButton.center.y);
float originalCenterX = topSubmitButton.center.x;
float originalCenterY = topSubmitButton.center.y;

if (commentViewUp) {
    rect.origin.y = self.view.frame.origin.y + 80;// move down view by 80 pixels
    commentViewUp = NO;

    CGPoint newCenter = CGPointMake( 57.0f , 73.0f); // better to calculate this if you are going to rotate to landscape

    [UIView beginAnimations:nil context:nil]; 
    [UIView setAnimationDuration:0.5f];
    topSubmitButton.center = newCenter;
    [UIView commitAnimations];

} else { // toggling the view's location
    rect.origin.y = self.view.frame.origin.y - 80;// move view back up 80 pixels
    commentViewUp = YES;


    CGPoint newCenter = CGPointMake(160 , 74.0f + topSubmitButton.center.y);// would like to calculate center
    [UIView beginAnimations:nil context:nil]; 
    [UIView setAnimationDuration:0.5f];
    topSubmitButton.center = newCenter;
    [UIView commitAnimations];
  }

self.view.frame = rect;

[UIView commitAnimations];

}

如果您能告诉我如何将视图的中心放在CGPoint的x值中,那么可以获得奖励。

1 个答案:

答案 0 :(得分:1)

您可以使用静态变量在方法调用之间保留其内容。但是,初始化程序必须是常量,因此您无法调用方法来初始化它。您可以做的是使初始值无效,并在设置变量之前对其进行测试。

-(IBAction)scrollForComment {
    static float originalCenterX = −1, originalCenterY = −1; // Assuming −1 would be an invalid value
    if(originalCenterX == −1 && originalCenterY == −1) {
        CGPoint temp = topSubmitButton.center;
        originalCenterX = temp.x;
        originalCenterY = temp.y;
    }
    ...
  

如果您能告诉我如何将视图的中心放在CGPoint的x值中,那么可以获得奖励。

我不确定你的意思。如果您只想设置中心的x坐标,则需要获取当前中心,更改x坐标,并保存新点。

CGPoint temp = topSubmitButton.center;
temp.x = newXValue;
topSubmitButton.center = temp;