Objective-C自定义UITabBar位置

来源:互联网 发布:replay直播软件 编辑:程序博客网 时间:2024/06/12 22:20

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

效果:
这里写图片描述

0 0