Reputation: 1104
I'am trying to make a simple application, for making a better understanding of Obj-C.
What I trying to accomplish is the functionality to change the picture of my UIImageView when touches ended. This is a simple task, with a static functionality circle.image = [UIImage imageNamed:@"newImage.png"];
But I need it to be dynamic, so i don't need to type this line for every image.
I have been using [touch view]
(see sample code below) in some cases, but this is not possible for changing image: Property 'image' not found on object of type UIImage
I hope someone can give me alternative and I will really appreciate some sample code, thanks in advance :)
ViewController.h:
@interface ViewController : UIViewController{
IBOutlet UIImageView *circle;
IBOutlet UIImageView *triangle;
IBOutlet UIImageView *star;
IBOutlet UIImageView *background;
}
ViewController.m
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [[event allTouches] anyObject];
if([touch view] != background){
[touch view].image = [UIImage imageNamed:@"newImage.png"];
}
}
Upvotes: 0
Views: 639
Reputation: 163
Try this:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [[event allTouches] anyObject];
if([touch view] != background){
UIImageView *selected = (UIImageView *)[touch view];
selected.image = [UIImage imageNamed:@"newImage.png"];
}
}
Upvotes: 1
Reputation: 104082
You shouldn't use "==" to compare objects (only primitives). In any case, it would be better to check for whether the object is an image view:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [[event allTouches] anyObject];
if([touch.view isKindOfClass:[UIImageView class]]){
[(UIImageView *)[touch view] image] = [UIImage imageNamed:@"newImage.png"];
}
}
If you have other image views in your view that you don't want to have participate in this image change, then you might want to give the image views you do want to change, tags, and check the tag value in the if statement instead.
Upvotes: 1
Reputation: 25459
Your code doesn't know that [touch view] is uiimageview subclass it thinks that it's uiview and there is no image property for uiview so you have an error. You should do something like that:
if([touch view] != background){
if([touch view] == circle)
circle.image = [UIImage imageNamed:@"newImage.png"];
else if([touch view] == triangle)
triangle.image = [UIImage imageNamed:@"newImage.png"];
else if([touch view] == star)
star.image = [UIImage imageNamed:@"newImage.png"];
}
Upvotes: 0