gadgetmo
gadgetmo

Reputation: 3172

setImage: does not cause image to change

I have created two UIImageViews in my code:

UIImageView *background = [[UIImageView alloc]initWithFrame:CGRectMake(150, 60, 180, 180)];
UIImageView *result = [[UIImageView alloc]initWithFrame:CGRectMake(150, 60, 180, 180)];
[self.view addSubview:background];
[self.view addSubview:result];
[self.view insertSubview:result aboveSubview:background];

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[background setImage:[UIImage imageNamed:[defaults objectForKey:@"colour"]]];

When you press a button, this code is executed:

- (IBAction)oneToSix {
    int rNumber = (arc4random() % 6) + 1;
    [result setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d", rNumber, @".png"]]];
}

but the image doesn't change.

Also, I am getting these errors:

errors

Upvotes: 1

Views: 685

Answers (3)

Jim
Jim

Reputation: 73966

[result setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d", rNumber, @".png"]]];

Note you are only putting the number into that string. You'll want %d%@ as the format.

Those aren't errors, they are warnings. You have an instance variable in your class called background. You also declare a local variable called background in your method. The warning is to let you know that there's a conflict and that it's choosing the local variable over the instance variable.

Upvotes: 1

Sergio Campamá
Sergio Campamá

Reputation: 746

Is the image named Red or Red.png? Because if it is the latter, you should append the file extension in the setImage method with something like [NSString stringWithFormat:@"%@.png", [defaults objectForKey:"colour"]]

Also, you are inserting the result imageView twice. Remove the first one.

Upvotes: 0

jv42
jv42

Reputation: 8593

You are redeclaring variables in the method scope that were already defined at the class scope. Remove the UIImageView * part from your initialization.

Note: it's doing nothing when you change image, because in ObjectiveC, a method call to nil (uninitialized instance member) is valid, and produces no visible result.

Upvotes: 4

Related Questions