Search code examples
iosobjective-caddsubview

IOS Adding subview from other class programatically


i've tried to create a custom view which works like a bottom bar and it worked

Right now this function is required on multiple classes, so i try writing it into a new class and import it which likes:

//BottomBarLauncher.h
#import <UIKit/UIKit.h>

@interface bottomBarLauncher : UIViewController
-(void)launchBottomBar;
@end

And implement it as :

//BottomBarLauncher.m
-(void) launchBottomBar{
    for (UIView *subView in [topView subviews]) {
        [subView removeFromSuperview];
    }
    UIView *btnBarView = [[UIView alloc]initWithFrame:CGRectMake(0,     self.view.frame.size.height - 53.3, 320, 53.3)];
    btnBarView.backgroundColor = [UIColor redColor];
    [self.view addSubview:btnBarView];
}

Now here's the problem, while i try implement it on a new view like follows:

//NewView.m
#import "BottomBarProtocol.h"

@interface NewView()
{
    BottomBarLauncher *btnBar;
}
@end
//blahblahblah

[btnBar launchBottomBar];

and nothing happens, i think the problem was with

[self.view addSubview:btnBarView];

but i have no idea how to select the current view as target which i can add subview onto.


Solution

  • First a suggestion, looking at your requirements/code I think you want to create custom view. For creating a custom view, create a class which inherits from UIView rather than creating a UIViewController.

    Now moving to the code, your btnBar is a UIViewController which has its own view self.view so when you call this [btnBar launchBottomBar] internally you are adding the bottom bar on self.view that is your btnBar controllers view and not on NewView controllers view. Hope you understand what I am pointing out.

    Here you are missing out few calls,

    btnBar.view.frame = CGRectMake(0,self.view.bounds.size.height-40,self.view.bounds.size.width,40); // Add suitable frame.
    
    //This call will add the btnBar's view as subview onto your current view controller's view.
    [self.view addSubView:btnBar.view];
    

    This is not correct/recommended way and you can face serious challenges regarding memory leaks. To avoid those mistakes, as I suggested, create a custom UIView instead. Take a look around on how to create custom views.

    Hope that helps!