Can I have multiple views per viewController?

Here is a related question I found, but it does not answer my question in detail.

[http://stackoverflow.com/questions/3209993/cocoa-touch-can-i-have-multiple-views-per-view-controller-or-specify-bounds-of][1]

I have a UIView class, BallView, which is set to be the default view of the ballViewController. Now, this view has a ball bouncing around according to the accelerometer. I am calling a private function draw every time the accelerometer sends updates.

However, my main question is: I would like to have multiple such balls bouncing around.

Do I have to recreate the view for every class ? But then the File's Owner's IBOutlet view will also have to be connected. And an IBOutlet can point to just one address.

Any other way round this ?

Here is how I'm instantiating the Ball View class in the ballViewController:

[motionManager startAccelerometerUpdatesToQueue:queue withHandler:
 ^(CMAccelerometerData *accelerometerData, NSError *error){
     [(BallView *)self.view setAcceleration:accelerometerData.acceleration];
     [(BallView *)self.view performSelectorOnMainThread:@selector(draw) withObject:nil waitUntilDone:NO];
 }];

Thus, it means, my question is a bit different from those multi-view tab-bar solutions. Because in those cases only 1 view is shown at a time. I want 4-5 views overlaid on top of each other.

Any help ?

Upvotes: 0

Views: 4662

Answers (1)

Mac
Mac

Reputation: 14791

You're right, your view controller can only have a single UIView in its view property. That view though can certainly be used to contain other subviews.

What I would do is have a plain old UIView as your controller's view, and have your BallViews be subviews of that view. Your controller can still control those views, they ust can't all be in its view property.

EDIT: If you're using nib files/Interface Builder, adding a BallView as a subview of your controller's view is pretty easy - just drag a UIView object onto the view, and in the identity inspector you can change the identity of the view to your BallView class.

If you're not using IB, you can also do the same programatically:

// BallViewController.h
@interface BallViewController
{
    BallView* ballView;
}

@end

// BallViewController.m
@implementation BallViewController

- (void) loadView
{
    ...

    CGRect frame1 = ...
    CGRect frame2 = ...

    self.view = [[UIView alloc] initWithFrame:frame1];

    ballView = [[BallView alloc] initWithFrame:frame2] retain];
    [self.view addSubview:ballView];

    ...
}

@end

Upvotes: 4

Related Questions