1

这应该很容易。

我有一种上下移动视图的方法,在此过程中,我上下移动了一个 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 值中,那就太好了。

4

1 回答 1

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;
于 2011-07-17T21:57:23.877 回答