Reputation: 35
Im learning Xcode and i was wondering how to make a button refresh part of my code or something. Im placing a picture in a random location on my screen but i want to be able to press the button to relocate it to another random location, any input would be greatly appreciated. Thanks. This is my code. ViewController.m
- (void)viewDidLoad
{
int xValue = arc4random() % 320;
int yValue = arc4random() % 480;
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(xValue, yValue, 70, 30)];
NSString *imgFilepath = [[NSBundle mainBundle] pathForResource:@"clubs-2-150" ofType:@"jpg"];
UIImage *img = [[UIImage alloc] initWithContentsOfFile:imgFilepath];
[imgView setImage:img];
[self.view addSubview:imgView];
[super viewDidLoad];
}
Upvotes: 2
Views: 49
Reputation: 5903
As your code stands right now it is not possible Variables have a scope, that means, they only exists within certain functions or classes. You variable imgView
only exists on viewDidLoad
. For you to be able to access it somewhere else you need to declare it as an instance variable.
on your .h file to this:
@interface yourClassName : UIViewController {
UIImage *imageIWantToChange;
}
This will let you access imageIWantToChange in all of your yourClassName functions.
Now, on your .m
- (void)viewDidLoad
{
[super viewDidLoad];
int xValue = arc4random() % 320;
int yValue = arc4random() % 480;
//Notice that we do not have UIImage before imageIWantToChange
imageIWantToChange = [[UIImageView alloc] initWithFrame:CGRectMake(xValue, yValue, 70, 30)];
UIImage *img = [UIImage imageNamed:@"clubs-2-150.jpg"];
[imageIWantToChange setImage:img];
[self.view addSubview:imgView];
}
Then in your IBAction or button selector:
-(IBAction) buttonWasPressed:(id) sender {
CGRect frame = imageIWantToChange.frame;
frame.origin.x = arc4random() % 320;
frame.origin.y = arc4random() % 480;
imageIWantToChange.frame = frame;
}
Upvotes: 2