Joon. P Joon. P - 1 year ago 115
Objective-C Question

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:


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

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

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


#import <Foundation/Foundation.h>

@interface myUIViewClass : NSObject

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


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:


- (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:


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

Not right 2:


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

Not right 3:


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

So confused!

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download