Search code examples
objective-ccocoa-touchuiviewaddsubview

Adding a sub-view appears to do nothing


In my application, when the user clicks an infoButton, it should add another view to the screen at a specific location. I'm trying to achieve this behavior with the following method:

- (IBAction)showInfo1:(id)sender
  {
    UIView *myView1 = [[UIView alloc] initWithFrame:CGRectMake(25,25,50,20)];   
    [self.view addSubview:myView1]; 
  }

(I declared everything in the header file of my class.)

When I run the code and press the button, nothing appears to happen (I don't see the new view).

I also noticed that XCode is displaying the following warning:

Local declaration of 'myView1' hides instance variable.

Does anyone have any ideas?


Solution

  • How do you know nothing changes?

    It looks like myView1 doesn't actually contain anything. Try setting the background color of myView1

    - (IBAction) showInfo1: (id) sender
    {
        UIView *myView1 = [[UIView alloc] initWithFrame:CGRectMake(25,25,50,20)];   
        myView1.backgroundColor = [UIColor redColor];
        [self.view addSubview: myView1]; 
    }
    

    To open it at a specific point you need to change the parameters in CGRectMake() for example

    to open it at the very top left with a width of 50 and height of 20 you would do:

    CGRectMake(0, 0, 50, 20)