这应该很容易。在方法中保留变量
我有一种方法来上下移动视图,同时这样做,我上下移动一个UIButton ...然后再次将该按钮移回原始位置。
我想我可以用float 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值。
我猜你会想值存储在一个成员变量或全局变量(取决于如果您有一个成员函数,或整体功能上)。我不太了解Objective-C,所以我不会发布这个答案。 –
此外,您可以通过取宽度,除以2,并添加到矩形左侧的x偏移量来获得任何类型矩形的“中心”(例如,如果它移动了一些单位在右边)。 –