Joon. P
Joon. P

Reputation: 2298

Send data TO UIView FROM UIViewController?

Very big confusion I couldn't resolve whatsoever...

I might be confused over some basic stuffs.. but I just can't make it straight

There are two things here

  1. UIViewController
  2. UIView object inside UIViewController

Here is what I did:

1) create a project of Single View -> from the storyboard, I dragged out UIView onto UIViewController

2) new->file to create myUIViewClass.h and myUIViewClass.m which is subclass of UIView.

3) assign "Custom Class" of UIView, which I dragged out, to myUIViewClass

4) back in the UIViewController, control+drag that UIView to my myUIViewController.h and make it an outlet like this:

myUIViewController.h

#import <UIKit/UIKit.h>
#import "myUIViewClass.h"

@interface myUIViewController : UIViewController
@property (strong, nonatomic) IBOutlet myUIViewClass *uiview;
@end

4) create property inside myUIViewClass.h which will do some drawing to UIView directly:

myUIViewClass.h

#import <Foundation/Foundation.h>

@interface myUIViewClass : NSObject

//I want to use this array in - (void)drawRect:(CGRect)rect {} method.
@property (nonatomic, strong) NSArray *arrayInsideUIView;

@end 

4) inside myUIViewClass.m, since it's the subclass of UIView, there is this line of code which gets called when I run the project:

myUIViewClass.m

- (void)drawRect:(CGRect)rect {
    NSLog(@"drawing starts");
}

5) Now, I want this to be something like:

- (void)drawRect:(CGRect)rect {
    NSLog(@"data to draw with: %@", _arrayInsideUIView);
}

6) But before doing this, I would need to populate _arrayInsideUIView. I want to do this from myUIViewController.m

7) How do i do this?

Not right 1:

myUIViewController.m

- (void)viewDidLoad {
    _uiview = [UIView alloc] init];
    _uiview.arrayInsideUIView = @[@"one", @"two"]; 
    //the array is not inside UIView, but inside myUIViewClass
}

Not right 2:

myUIViewController.m

- (void)viewDidLoad {
    _uiview = [[myUIViewClass alloc] init];    
    [self.view addSubview: _uiview]; 
    //this creates duplicate UIView's
}

Not right 3:

myUIViewController.m

- (void)viewDidLoad {
    myUIViewClass *uiviewclass = [[myUIViewClass alloc] init];
    uiviewclass.arrayInsideUIView = @[@"one", @"two"]; 
    //No UIView gets created here
}

So confused!

Upvotes: 2

Views: 360

Answers (1)

Fonix
Fonix

Reputation: 11597

all you should need to do is the following:

- (void)viewDidLoad {
    [super viewDidLoad]; //dont forget this
    self.uiview.arrayInsideUIView = @[@"one", @"two"];
}

because the view is hooked up to the storyboard, the storyboard handles the creation of the view, so there is no need to alloc/init it yourself.

and if you do alloc init it yourself (which you are currently doing), you are replacing the one the storyboard setup so would have to completely set it up from scratch yourself (frame position etc) which is probably not what you want.

Upvotes: 3

Related Questions