Creating Subviews

Discussion in 'iOS Development' started by cybohemia, Jan 29, 2009.

  1. cybohemia

    cybohemia New Member

    Joined:
    Jan 25, 2009
    Messages:
    49
    Likes Received:
    0
    Device:
    iPhone 3G (Black)
    I'm trying to figure out how to create subviews and I'm probably missing something basic...

    I've got a MainViewController, which points to a view of class AView (which is a UIView subclass). I have another class call BView (also a UIView subclass), which I want as AView's subview.

    BView has a field called num, which tells it what to display; num is set by AView when it creates BView.

    My problem is, num seems to lose it value (reset to 0) when BView is actually shown.

    I'm a noob and I'm probably doing a lot of bad/wrong things (like putting the creation code in drawRect) but I'm just trying get things to work, first.

    ----- AView.m -----
    - (void)drawRect : (CGRect)rect {
    BView *bv = [[BView alloc] init:2];
    NSLog(@"bv.num is %d", bv.num); // shows 2, as expected
    [self addSubview:bv];
    [bv release];
    }

    ----- BView.m -----
    - (void)drawRect : (CGRect)rect {
    NSLog(@"num is %d", num); // shows 0 instead of 2
    }

    ----------------------

    Can anybody tell me how to do this properly?

    Thanks!
  2. SkylarEC

    SkylarEC Super Moderator Emeritus Staff Member

    Joined:
    Sep 19, 2007
    Messages:
    6,642
    Likes Received:
    129
    UIView *aView = [[UIView alloc] initWithFrame:aRect];
    UIView *anotherView = [[UIView alloc] initWithFrame:anotherRect];

    [self.view addSubview:aView];
    [self.view addSubview:anotherView];

    [aVeiw release];
    [anotherView release];


    Put that anywhere, like viewDidLoad, viewWillLoad, viewWillAppear, viewDidAppea, or any other method you want. Those four are standard view controller methods that you can override. Just don't forget to pass the function onto the superclass. Ie, - (void)viewWillAppear

    Please Register or Log in to view images

    BOOL)animated { [super viewWillAppear:animated]; /*the rest of your code*/ }
  3. cybohemia

    cybohemia New Member

    Joined:
    Jan 25, 2009
    Messages:
    49
    Likes Received:
    0
    Device:
    iPhone 3G (Black)
    Thanks for the code, SkylarEC - it worked!

Share This Page