gpt4 book ai didi

objective-c - 在方法中保留变量

转载 作者:行者123 更新时间:2023-11-29 13:47:29 25 4
gpt4 key购买 nike

这应该很容易。

我有一种上下移动 View 的方法,在这样做的同时,我上下移动了一个 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];

}

如果你能告诉我如何将 View 的中心置于 CGPoint 的 x 值中,则加分。

最佳答案

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

-(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;
}
...

Bonus if you can tell me how to put the center of a view in a CGPoint's x value.

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

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

关于objective-c - 在方法中保留变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6727013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com