user3339697
user3339697

Reputation:

UIImageView Created Programmatically

I am trying to create a UIImageView but I have to make it programmatically and I have to be able to declare it with an instance variable (in the .h file or something of the sort). Here is the code for creating it; however, this does not allow me to use it in other methods.

UIImageView *airImage = [[UIImageView alloc] 
                            initWithFrame:CGRectMake(29, 7, 82, 96)];
[myScrollView addSubview:airImage];

I have looked on other people asking similar questions however none of them will allow me to create an instance variable. BTW that code is in my viewDidLoad. Thanks in advance!

Upvotes: 1

Views: 79

Answers (3)

PCoder123
PCoder123

Reputation: 364

In your .h use:

UIImageView *airImage;

In your viewDidLoad:

airImage=[[UIImageView alloc] initWithFrame:CGRectMake(29, 7, 82, 96)];
[myScrollView addSubview:airImage];

Or you can declare it as a property:

@property (nonatomic, strong) UIImageView *airImage;

and use to access it:

self.airImage = [[UIImageView alloc] initWithFrame:CGRectMake(29, 7, 82, 96)];
[myScrollView addSubview:self.airImage];

Upvotes: 1

Fede Cugliandolo
Fede Cugliandolo

Reputation: 1686

in your .h

@property (nonatomic, strong) UIImageView *airImage; // public

in your .m (viewDidLoad or wherever you want to init your ImageView)

self.airImage = [[UIImageView alloc] initWithFrame:CGRectMake(29, 7, 82, 96)];
[myScrollView addSubview:self.airImage];

Upvotes: 0

erdekhayser
erdekhayser

Reputation: 6657

To be more specific, instance variables should be created in a specific place in an interface (can be both in your .h and .m files, but use .h as it is more common).

If you want to declare it in your .h file, then you will want your code to look like this:

@interface ClassName : UIViewController {
    UIImageView *_airImage; //many developers use _ to represent ivars
}

@end

To set the value of the variable, then you can use

_airImage = [[UIImageView alloc]init...];

Property's are another option. Instead, you can declare this like so:

@interface ClassName : UIViewController

@property (strong, nonatomic) UIImageView *airImage;

@end

To set this value, simply use,

self.airImage = [[UIImageView alloc]init...];

Hope this helped clear some things up. Use this question to help understand the difference and when to use ivars vs properties: What is the difference between ivars and properties in Objective-C

This tutorial shows how you can use both ivars and properties together, and just help you understand them both better: http://www.icodeblog.com/2011/07/13/coding-conventions-ivars/

Upvotes: 0

Related Questions