Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/119.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Iphone 以与arc4random相同的方法使用计数器会使按钮保持静止。(iOS)_Iphone_Ios_Xcode_Counter_Arc4random - Fatal编程技术网

Iphone 以与arc4random相同的方法使用计数器会使按钮保持静止。(iOS)

Iphone 以与arc4random相同的方法使用计数器会使按钮保持静止。(iOS),iphone,ios,xcode,counter,arc4random,Iphone,Ios,Xcode,Counter,Arc4random,我有一个按钮,我想随机显示在屏幕上,每次按下它。我使用arc4random来实现这一点。但一旦我在这个方法中加入了一个计数器,随机部分就停止工作了。任何关于为什么会发生这种情况或如何解决它的想法都将不胜感激,提前感谢!我的代码如下 -(IBAction)random:(id)sender{ int xValue = arc4random() % 320; int yValue = arc4random() % 480; button.center = CGPointM

我有一个按钮,我想随机显示在屏幕上,每次按下它。我使用arc4random来实现这一点。但一旦我在这个方法中加入了一个计数器,随机部分就停止工作了。任何关于为什么会发生这种情况或如何解决它的想法都将不胜感激,提前感谢!我的代码如下

-(IBAction)random:(id)sender{

    int xValue = arc4random() % 320;
    int yValue = arc4random() % 480;

    button.center = CGPointMake(xValue, yValue);

    counter = counter + 1;
    score.text = [NSString stringWithFormat:@"Score: %i", counter];


}

实际上,不是计数器暴露了问题,而是标签中的值设置。这是自动布局的一个问题,当您设置标签的值时,它会强制视图的布局,并且自动布局功能会将按钮移回其原始位置。最简单的修复方法是关闭自动布局,这是通过IB中的文件检查器(最左边的一个)完成的——只需取消选中“使用自动布局”框

它发生得太快,看不到发生了什么,但如果您将代码更改为此(自动布局仍处于启用状态),您将看到按钮移动,然后跳回:

-(IBAction)random:(id)sender{
    int xValue = arc4random() % 320;
    int yValue = arc4random() % 480;
    button.center = CGPointMake(xValue, yValue);
    counter = counter + 1;
    [self performSelector:@selector(fillLabel) withObject:nil afterDelay:.5];

}

-(void)fillLabel {
    score.text = [NSString stringWithFormat:@"Score: %i", counter];
}
如果要使用布局约束,另一种方法是更改布局约束的“常量”参数。在下面的示例中,我将按钮放置在这样一个位置(在IB中),它对superview具有左上约束。我对这些约束进行了修改,并将它们连接起来。代码如下:

@implementation ViewController {
    IBOutlet UILabel *score;
    int counter;
    NSLayoutConstraint IBOutlet *leftCon;
    NSLayoutConstraint IBOutlet *topCon;
}

-(IBAction)random:(id)sender{
    int xValue = arc4random() % 300;
    int yValue = arc4random() % 440;
    leftCon.constant = xValue;
    topCon.constant = yValue;
    counter = counter + 1;
    score.text = [NSString stringWithFormat:@"Score: %i", counter];
}

你说“问题”,我说“有用的特性”;)但这可能就是正在发生的事情。@jrturton,只是自动布局处女的问题;)这就成功了,谢谢@Dave123,我添加了另一种方法,如果您想使用约束进行操作的话。