NSTimer移动按钮

时间:2013-01-27 01:54:15

标签: ios objective-c button nstimer

我的目标是创建一个按钮,无论何时按下该按钮都会将其移动到随机位置。我得到了这个动作:

- (IBAction)move:(id)sender 
{
   int x = 0 + arc4random() % (260 - 0);
   int y = 0 + arc4random() % (400 - 0);

   frame = self.button.frame;
   frame.origin.x = x; // new x coordinate
   frame.origin.y = y; // new y coordinate
   self.button.frame = frame;
}

然而,我尝试添加一个计时器,由一个按钮触发:

- (IBAction)start:(id)sender 
{
   timer =[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];
   self.startButton.Hidden = YES;
   self.label.hidden = NO; 
}

- (void)showActivity
{

   int currentTime = [self.label.text intValue];
   int newTime = currentTime - 1;
   self.label.text = [NSString stringWithFormat:@"%d", newTime];

   if (newTime == 0)
   {
       [timer invalidate];
   }
}

每次计时器滴答时,它似乎重新绘制视图。在我启动计时器之前,按钮可以移动得很好。然后,一旦我按下启动计时器的第二个按钮,第一个按钮就会根据我最初放在我的xib文件中的位置。有什么方法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

这个怎么样......

- (void)repositionViewRandomly:(UIView *)view {

    CGFloat width = view.bounds.size.width;
    CGFloat height = view.bounds.size.height;

    int x = arc4random() % (int)(view.superview.bounds.size.width - width);
    int y = arc4random() % (int)(view.superview.bounds.size.height - height);

    [UIView animateWithDuration:0.5 animations:^{
        view.frame = CGRectMake(x, y, width, height);
    }];
}

- (IBAction)buttonPressed:(id)sender {

    [self performSelector:@selector(repositionViewRandomly:) withObject:sender afterDelay:1.0];
}

答案 1 :(得分:0)

此问题可能是自动布局的结果(iOS 6功能根据称为约束的算术规则控制控件的放置)。要查看是否启用了自动布局,请打开故事板/ NIB,按选项 + 命令 - 1 转到"文件检查员" (或者只需点击"文件检查器"标签,第一个,在最右边的面板上),看看" autolayout"检查与否。

如果启用了autolayout,即使在更改帧之后,也会重新应用约束,并且控件将移回到约束所指示的位置。您可以关闭自动布局,也可以启用autolayout,并以编程方式删除约束或以编程方式更改约束,而不是更改框架。

有关如何通过更改约束进行动画处理的示例,请参阅此answer。但最简单的方法就是关闭autolayout:

autolayout setting

有关自动播放的背景信息和各种来源的链接,请参阅Cocoa Auto Layout Guide