Ios 更改图像后,如何将UIButton保持在同一位置?

Ios 更改图像后,如何将UIButton保持在同一位置?,ios,uibutton,Ios,Uibutton,我有一个ui按钮,可以在点击后更改屏幕上的位置。然后用户单击另一个按钮来更改按钮的图像,我希望它保持在新位置。目前,在更改图像后,我的代码将恢复到原始位置。代码如下: 首先移动按钮(newLocation是UIImageView的位置): 然后单击其他按钮更改按钮图像: [movableButton setImage:[UIImage imageNamed: @"differentImage.png"] forState:UIControlStateNormal]; 好的,现在我有你的问题了,

我有一个
ui按钮
,可以在点击后更改屏幕上的位置。然后用户单击另一个按钮来更改按钮的图像,我希望它保持在新位置。目前,在更改图像后,我的代码将恢复到原始位置。代码如下:

首先移动
按钮
(newLocation是
UIImageView的位置
):

然后单击其他按钮更改按钮图像:

[movableButton setImage:[UIImage imageNamed: @"differentImage.png"] forState:UIControlStateNormal];

好的,现在我有你的问题了,你可以做的是在第二个按钮的动作中启动一个计数器:

-(void)secondButtonClick
{
 static int counter = 1;
   if(counter %2  == 0) 
   {
     firstButton.center =cgpoint a;  // a gain some point where you wan't to place the center
    }
 if(counter %2 != 0)
    {
      [firstButton setBackgroundImage:[UIImage imageNamed:@"logout.png"] forState:UIControlStateNormal];
     }
计数器++

}
您可以在更改图像之前修改是否要更改位置的条件。。。。。此外,uou还可以像这样更改中心

a.x =a.x+10;
a.y =a.y +10;
myButton.center = a;
试试这个

-(IBAction) movingButtonClicked
{
      [movingButton setFrame:CGRectMake(movingButton.frame.origin.x+10,movingButton.frame.origin.y+20,50,50)];
}

-(IBAction) changeImage
{
     [movingButton setImage:[UIImage imageNamed: @"differentImage.png"] forState:UIControlStateNormal];
}

我不明白它为什么移动。我刚测试过它,它确实动了。我需要调查一下它为什么会移动,然后再给你回复

但这将解决它移动的问题

CGPoint currentLoc = self.imageButton.center;
[self.imageButton setImage:[UIImage imageNamed:@"face"] forState:UIControlStateNormal];
self.imageButton.center = currentLoc;

尝试关闭自动布局。更多的代码可能有助于准确跟踪错误。我知道关闭autolayout会更正问题,但我希望在项目中使用autolayout。然后您可以尝试修复按钮的框架。例如:
movableButton.frame=CGRectMake(position.x,position.y+10,size.width,size.height)基本上有两个按钮,一个(按钮1)更改(位置和图像),另一个进行更改(按钮2)。按下按钮2时,会更改第一个按钮的位置。再次按下时,图像会发生变化。问题是,当我第二次按下它时,它会改变图像,它也会恢复到原来的位置。谢谢你,这是我发现唯一有效的方法。听起来这可能是一个解决办法,因此如果您找到一个更简单的方法,请让我知道。如果您使用的是自动布局,您不应该直接修改
中心
框架
。您应该更新约束以考虑按钮的新大小。按钮移动的原因是,在某个点上,约束正在重新计算,而解算器将忽略您手动设置的位置。
CGPoint currentLoc = self.imageButton.center;
[self.imageButton setImage:[UIImage imageNamed:@"face"] forState:UIControlStateNormal];
self.imageButton.center = currentLoc;