I have a custom UIView
class. Inside it I have declared an IBOutlet
property for UIImageView
.
#import <UIKit/UIKit.h>
@interface SettingItem : UIView{
}
@property (strong, nonatomic) IBOutlet UIImageView *myImage;
@end
Now i am using storyboard. There is a viewcontroller. I dragged UIView
to viewcontroller. I dragged one UIImageView
as a subview of above UIView
. I set the "SettingItem" class to UIView
from storyboard. I connected the outlet to myImage by normal dragging from outlets of SettingItem
from utilities window.
SettingItem
implementation#import "SettingItem.h"
@implementation SettingItem
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[self baseInit];
}
return self;
}
-(id) initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if (self) {
// Initialization code
[self baseInit];
}
return self;
}
- (void) baseInit{
NSLog(@"myImage %@"self.myImage);
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
@end
Now my problem is myImage
is always nil
, above NSLog
just print (null)
for the outlet. I checked the view in storyboard and checked its outlet reference and its pointing to myImage
. I am missing something. I googled for the help but couldn't find any solution.
Can you please point out what am i doing wrong ?
Override awakeFromNib in your view - this is the first lifecycle method to be called after the IBOutlets have been assigned and is the right place for your code.
initialize them in awakeFromNib:
- (void)awakeFromNib
{
//init code
}
I just had the exact same problem and the solution is really easy:
You're accessing myImage
to soon - that's it.
Withing -(id) initWithCoder:(NSCoder *)aDecoder{
and - (id)initWithFrame:(CGRect)frame
the UIView
is not already drawed. So myImage is not initalized yet.
You can test it if you add a UIButton
and an IBAction
and do something like this:
- (IBAction)buttonClicked:(id)sender {
NSLog(@"%@",myImage);
}
And you'll see how myImage
is not nil
anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With