Objective-C自定义UITabBar位置

UITabBar是开发中常用到的控件,一般应用在底部,少数有在顶部的,但UITabBar得frame的属性是readonly的不能直接修改,但是可以通过layoutSubviews来实现自定义位置

新建一个类继承自UITabBar

.h文件代码:

@interface MytabBar : UITabBar
- (instancetype)initWithFrame:(CGRect)frame;
+ (instancetype)banBar;
@end

.m文件代码:

#import "MytabBar.h"

@implementation MytabBar

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
    }
    return self;
}

+ (instancetype)banBar{
    return [[self alloc]init];
}

- (void)layoutSubviews{

    CGRect frame = self.frame;
    frame.origin.y = 20;
    self.frame = frame;

    self.backgroundColor = [UIColor whiteColor];
    for (int i = 0; i < 4; i++) {
        UIView *tabBarButton = self.subviews[i];
        //设置位置
        CGRect frame = tabBarButton.frame;
        frame.origin.x = i * (self.frame.size.width)/4;
        frame.origin.y = 0;
        //设置大小
        frame.size.width = self.frame.size.width / 4;
        frame.size.height = self.frame.size.height;
        tabBarButton.frame = frame;
    }
}
@end

在根视图中引用:

#import "MytabBar.h"

#define kMycolor [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1]

@interface MytableBarController ()
@end

@implementation MytableBarController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIViewController *VC1 = [[UIViewController alloc]init];
    [self addChildViewControllerWithViewController:VC1 title:@"第一页" ImageName:@"1.jpg"];

    UIViewController *VC2 = [[UIViewController alloc]init];
    [self addChildViewControllerWithViewController:VC2 title:@"第二页" ImageName:@"2.jpg"];

    UIViewController *VC3 = [[UIViewController alloc]init];
    [self addChildViewControllerWithViewController:VC3 title:@"第三页" ImageName:@"3.jpg"];

    UIViewController *VC4 = [[UIViewController alloc]init];
    [self addChildViewControllerWithViewController:VC4 title:@"第四页" ImageName:@"4.jpg"];

    MytabBar *mytabBar = [[MytabBar alloc]init];
    [self setValue:mytabBar forKey:@"tabBar"];

}

- (void)addChildViewControllerWithViewController:(UIViewController *)childVC title:(NSString *)title ImageName:(NSString *)imageName{
    childVC.view.backgroundColor = kMycolor;//随机颜色
    childVC.tabBarItem.title = title;
    UIImage *image = [UIImage imageNamed:imageName];
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    childVC.tabBarItem.image = image;
    [self addChildViewController:childVC];
}
@end

效果:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值