Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C Create an instance of ViewController

I wanted to create an instance of the ViewController class with :

ViewController *viewConnection = [[ViewController alloc]init];

self.image.center = CGPointMake(self.image.center.x + 1, self.image.center.y);

if (CGRectIntersectsRect(self.image.frame, viewConnection.otherImage.frame)) {
    [self.movementTimer invalidate];
}`

it doesn't enters the if-statement when the image in the class hits the image in the ViewController , can somebody tell me why ?

like image 553
user2896263 Avatar asked Aug 20 '26 06:08

user2896263


1 Answers

To access the variables and outlets you have to define the propreties in .h file:

@interface ViewController : UIViewController
//Property
@property (nonatomic, copy) NSString *myString;
//Outlet
@property (nonatomic, weak) IBOutlet UILabel *myLabel;
@end

After that you can create object and access it properties:

ViewController *viewConnection = [[ViewController alloc]init];
viewConnection.myString = @"string";
viewConnection.myLabel.text = @"label text";

//Extended

In your example you create viewConnection object and after that you check it properties' frame:

viewConnection.otherImage.frame

but you haven't set it up, you haven't set up otherImage, you haven't set up it's frame so this is why you have the issue.

// Extended 2

The reason why it's doesn't work is because you try to change frame of the property (otherImage), I assume it's IBOutlet just after you initialised the view controller but the IBOutlets are created later in view controller lifecycle, you should chance the outlets in viewDidLoad or viewDidAppeare but this method fired after you present/push the view controller. So you should create variable, let's say CGRect and after you initialise view controller set up it value, after that push/present the view controller and in your class (ViewController), for example, in viewDidLoad set up otherImage.frame = variable.

like image 170
Greg Avatar answered Aug 21 '26 22:08

Greg