Jayasabeen Appukuttan
Jayasabeen Appukuttan

Reputation: 1440

Add subview in UITabBar

I want to customise UITabBar by subclassing it I am not able to get the UITabBar frame here is my code

in home_tabbar.h

#import <UIKit/UIKit.h>
@interface home_tabbar : UITabBar
-(void) changeFrame;
@end

in home_tabbar.m

#import "home_tabbar.h"
@implementation home_tabbar
- (void)viewDidAppear:(BOOL)animated {
   [self changeFrame];
}
- (void)changeFrame
{
   CGRect frame = self.viewForLastBaselineLayout.frame;
   NSLog(@"Frame x= %f y=%f width=%f height=%f",frame.origin.x,frame.origin.y,frame.size.width,frame.size.height);
}
@end

Upvotes: 1

Views: 2194

Answers (2)

DiegoQ
DiegoQ

Reputation: 1116

I have created a class to customize the UITabBar. In my case I had to add a background image and update the height. Here my code:

class DDTabBar: UITabBar {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        let backgroundImage = UIImageView(image: UIImage(named: "TabBar_Background"))
        backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
        var tabFrame = self.bounds
        tabFrame.size.height = 75
        backgroundImage.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        tabFrame.origin.y = self.bounds.size.height - 75
        backgroundImage.frame = tabFrame

        self.insertSubview(backgroundImage, at: 0)
    }
}

Upvotes: 0

Ashley Mills
Ashley Mills

Reputation: 53231

You can do it like this…

Subclass UITabBarController, and add a property for the view you want to add, a button in this case…

@property (strong, nonatomic) IBOutlet UIButton *videoButton;

Configure in viewDidLoad

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.videoButton.layer.cornerRadius = 4.0;
    self.videoButton.backgroundColor = [UIColor yellowColor];
    self.videoButton.clipsToBounds = YES;
    [self.tabBar addSubview: self.videoButton];
}    

then in viewDidLayoutSubviews

- (void) viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    // Only need to do this once if the orientation is fixed
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        self.videoButton.center = (CGPoint){CGRectGetMidX(self.tabBar.bounds), CGRectGetMidY(self.tabBar.bounds)};
    });

    // system moves subviews behind tab bar buttons, this fixes
    [self.tabBar bringSubviewToFront: self.videoButton];
}

Upvotes: 1

Related Questions