Search code examples
objective-ciosuiviewaddsubview

Back to basics - I want to import a UIView, but I cannot see it


As the title states, I am trying to import an UIView, but I can't get it to work. The first bit of code shows what I am trying to do without importing anything:

@interface ViewController : UIViewController
{

  UIView *firstUIView;
  UIView *secondUIView;

}

@end

@implementation ViewController

-(void)firstUIView
{
    firstUIView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 300)];
    firstUIView.backgroundColor = [UIColor redColor];
    [self.view addSubview:firstUIView];
}

-(void)secondUIView
{
    secondUIView = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 320, 100)];
    secondUIView.backgroundColor = [UIColor blueColor];
    [self.view addSubview:secondUIView];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
  // Do any additional setup after loading the view, typically from a nib.

    [self firstUIView];
    [self secondUIView];

}

@end

Now the following bit does not give the same result, but I want it to - where am I going wrong?

- (void)viewDidLoad
   {
     [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

     firstUIViewExternal *firstUIView = [[firstUIViewExternal alloc]     initWithFrame:CGRectMake(0, 0, 320, 300)];
     secondUIViewExternal *secondUIView = [[secondUIViewExternal alloc] init];


     [self.view insertSubview:firstUIView aboveSubview:self.view];
     [self.view addSubview:secondUIView];

    }

    @end

The code for the firstUIViewExternal and secondViewExternal are the same, with the name difference, as below:

-(void)secondUIView
 {
     secondUIView = [[UIView alloc] initWithFrame:CGRectMake(0, 100, 320, 100)];
     secondUIView.backgroundColor = [UIColor blueColor];
     [self addSubview:secondUIView];
 }

They are then imported with the #imported, declared used in the -(void)viewDidLoad method as above.

Why does the imported version not work?

I'll provide any extra info if needed. Thanks:-)

This is what I want to achieve with the importing of UIViews, but I am getting a blank white one:

enter image description here


Solution

  • There are 2 things i noticed in your code:

    1. You don't specify the frame size of your secondUIView.
    2. You only need to override the initWithFrame method in your "UIViewExternal" view and inherit from your UIView.

    The code of the views you want to import should look like this:

    .h:

    #import <UIKit/UIKit.h>
    @interface firstUIViewExternal : UIView
    @end
    

    .m:

    #import "firstUIViewExternal.h"
    @implementation
       - (id)initWithFrame:(CGRect)frame
       {
            self = [super initWithFrame:frame];
            if (self) {
                    // Initialization code
                    self.backgroundColor = [UIColor blueColor];
            }
            return self;
        }
    @end