2014-10-02 40 views
0

我正在xcode中构建一个非常基本的游戏。基本上 - 你需要在30秒内尽可能多的点击按钮,点击后无法让我的按钮在Objective C中移动。计时器和计数++似乎打扰它

我已经添加了代码来计算按钮被按下多少次,并添加了从30秒倒计时器标签的代码。

但是 - 我想让游戏稍微好一点,当按下按钮时,点击我的按钮在屏幕上移动。

我在网上发现了一段代码,使按钮在按下时随机移动。但是因为我将它添加到我的代码中,它不起作用。

我删除了按钮方法中的count ++,它可以工作,但是可以在定时器减少的时候回到原来的位置。

我删除了计时器,并且按钮工作正常,每次按下时它都在屏幕的不同部分。

我的问题是,为什么代码受到计时器的影响 - 更新标签,并且没有链接到按钮,为什么我不能计算按钮被按下的次数并将按钮移动到相同位置时间?

我附上我的代码以供参考 - 任何建设性的帮助将是伟大的!

#import "ViewController.h" 

@interface ViewController() 

@end 

@implementation ViewController; 

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { 
    [self setUpGame]; 
} 


- (void)viewDidLoad { 
    [super viewDidLoad]; 

    [self setUpGame]; 
} 



- (void)setUpGame { 
    seconds = 30; 
    count = 0; 

    timerLabel.text = [NSString stringWithFormat:@"Time: %li", (long)seconds]; 
    scoreLabel.text = [NSString stringWithFormat:@"Score\n%li", (long)count]; 


    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 
              target:self 
              selector:@selector(subtractTime) 
              userInfo:nil 
              repeats:YES]; 
} 

-(void)subtractTime { 
    seconds --; 
    timerLabel.text = [NSString stringWithFormat:@"Time: %li", (long)seconds]; 

    if (seconds == 0) { 
     [timer invalidate]; 

     UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Time is up!" message:[NSString stringWithFormat:@"You scored %li points", (long)count] delegate:self cancelButtonTitle:@"Play Again?" otherButtonTitles:nil]; 

     [alert show]; 
    } 
} 

-(IBAction)buttonPressed{ 

    count++; 

    scoreLabel.text = [NSString stringWithFormat:@"score\n%li", (long)count]; 

    _button.center = CGPointMake(arc4random() %100, arc4random() %200); 


} 

#import <UIKit/UIKit.h> 



@interface ViewController : UIViewController<UIAlertViewDelegate> { 
    IBOutlet UILabel *scoreLabel; 
    IBOutlet UILabel *timerLabel; 



    NSInteger count; 
    NSInteger seconds; 
    NSTimer *timer; 
} 
@property (weak, nonatomic) IBOutlet UIButton *button; 


- (IBAction)buttonPressed; 






@end 
+1

这可能是由于自动布局改变现在这些限制类似

self.leadingSpaceConstraint.constant = ... // some random value within reasonable limits self.topSpaceConstraint.constant = ... // some random value within reasonable limits 

紧随其后。如果您在IB中使用自动布局(默认情况下为自动布局),则不应通过设置框架来移动或调整视图大小,而应通过调整约束来调整视图大小。任何导致视图重绘的东西都会导致视图移回到由其约束定义的位置。 – rdelmar 2014-10-02 15:26:51

+0

谢谢 - 这是自动布局设置。 – ianlewis2010 2014-10-02 15:39:06

回答

0

我觉得rdelmar的想法是正确的。如果是这样,您可以执行以下操作:
在故事板中,给出按钮的约束:固定宽度,固定高度,固定超级视图的前导空间&固定顶级空间到超级视图。
而不是设置的按钮的中心性(这将通过自动布局被覆盖)的,限定在代码两个属性

@property (nonatomic, weak) IBOutlet NSLayoutConstraint *leadingSpaceConstraint; 
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *topSpaceConstraint; 

和在情节串连图板这些属性链接到您的约束。
你在哪里改前的中心物业,由

[UIView animateWithDuration:1.0 animations:^{ // some reasonable value instead of 1.0 
    [self.view layoutIfNeeded]; 
}]; 
相关问题