John John - 3 months ago 14
Objective-C Question

Use timer in a UIImageView Subclass

I want to change the picture of my custom UIImageView Subclass by a timer. But it doesn't work. Can you help me?

This is my code:

-(id)initWithCoder:(NSCoder *)aDecoder {

self = [super initWithCoder:aDecoder];
if (self) {
[self update];
}
return self;
}

-(void)update {

self.image = [UIImage imageNamed:@"Green.png"];
[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(change) userInfo:nil repeats:YES];

}

-(void)change {

self.image = [UIImage imageNamed:@"Red.png"];

}


Thanks!

Answer

use image property also to assign any image to imageView small rectification see below code.

Also do not give variable name same as its class property.

-(void)update {

    self.image.image = [UIImage imageNamed:@"Green.png"];
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(change) userInfo:nil repeats:YES];

}

-(void)change {
    self.image.image = [UIImage imageNamed:@"Red.png"];
}

self.image.image peoperty added here

Edit:

change your property from UIImage to UIImageView like see below

@property (strong, nonatomic) IBOutlet UIImageView *image;


.h Header file

#import <UIKit/UIKit.h>

@interface orientation : UIViewController
@property (strong, nonatomic) IBOutlet UIImageView *image;
@end

.m Message file

#import "orientation.h"

@interface orientation ()

@end

@implementation orientation

- (void)viewDidLoad {
    [super viewDidLoad];

    [self update];
    // Do any additional setup after loading the view.
}

-(void)update {

    self.image.image = [UIImage imageNamed:@"investment1.png"];
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(change) userInfo:nil repeats:YES];

}

-(void)change {
    self.image.image = [UIImage imageNamed:@"logout.png"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end