Using a counter in same method as arc4random causes button to remain stationary. (iOS) [closed]

StackOverflow https://stackoverflow.com/questions/14556933

سؤال

I have a button that I'd like to randomly display on the screen each time it is pressed. I'm using arc4random to make this happen. But once I incorporate a counter into this method, the random portion stops working. Any ideas why this is happening or how to fix it will be much appreciated, thanks in advance! My code is below.

-(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];


}
هل كانت مفيدة؟

المحلول

It's actually not the counter that's revealing the problem, but the setting of the value in your label. This is a problem with auto layout, and when you set the value of the label, it's forcing a layout of the views, and the auto layout feature is moving the button back to its original position. The easiest fix is to turn off auto layout, which is done from the File Inspector (the one furthest to the left) in IB -- just uncheck the "Uses Autolayout" box.

It happens too fast to see what's happening, but if you change your code to this (with auto layout still on) you will see the button move, and then jump back:

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

The other way to do it, if you want to use the layout constraints, is to change the "constant" parameter of the layout constraint. In the example below, I put my button in such a place (in IB) that it had a left and top constraint to the superview. I made IBOutlets to those constrains and connected them up. This is the code:

@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];
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top