HardBirch

【iPhone代码片段之八】如何自定义Tab Bar Button

时间:12-08-30 栏目:iOS移动应用开发技术 作者:张飞不张,文采横飞 评论:0 点击: 2,060 次

核心代码如下:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    CGRect frame = [[UIScreen mainScreen] bounds];
    //NSLog(@"x=%.2f,y=%.2f,width=%.2f,height=%.2f",frame.origin.x,frame.origin.y,frame.size.width,frame.size.height);
    self.window = [[UIWindow alloc] initWithFrame:frame];
    [[NSBundle mainBundle]loadNibNamed:@"TabBarController" owner:self options:nil];
    //[self.window addSubview:tabBarController.view];
    self.window.rootViewController = self.tabBarController;
    //添加中间的TabBarButton
    [self addCenternTabBarButton];

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    return YES;
}
-(void)addCenternTabBarButton{
    //NSLog(@"addCenternTabBarButton");
    //创建一个自定义button
    UIButton *centerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    //初始化button的背景图片
    UIImage *centerButtonImg = [UIImage imageNamed:@"centerTabBarItem.png"];
    //设置button的frame
    centerButton.frame = CGRectMake(0, 0, centerButtonImg.size.width, centerButtonImg.size.height);
    //设置button的背景图片
    [centerButton setBackgroundImage:centerButtonImg forState:UIControlStateNormal];
    //设置button的action
    [centerButton addTarget:self action:nil forControlEvents:UIControlEventTouchUpInside];

    CGFloat imageHeight = centerButtonImg.size.height;
    CGFloat barHeight = self.tabBarController.tabBar.frame.size.height;
    //NSLog(@"imageHeight=%2.f,barHeight=%.2f",imageHeight,barHeight);
    CGFloat delta = imageHeight-barHeight;
    //NSLog(@"delta=%.2f",delta);

    //设置centerButton的中心位置
    if(delta<=0){//如果图片高度小于等于TabBar高度
        centerButton.center = self.tabBarController.tabBar.center;
    }else{//如果图片高度大于TabBar高度
        CGPoint center = self.tabBarController.tabBar.center;
        center.y = center.y - delta/2.0;
        centerButton.center = center;
    }
    //将centerButton加入到tabBarController中
    [self.tabBarController.view addSubview:centerButton];
}

效果图如下:

声明: 本文由( 张飞不张,文采横飞 )原创编译,转载请保留链接: 【iPhone代码片段之八】如何自定义Tab Bar Button

【iPhone代码片段之八】如何自定义Tab Bar Button:等您坐沙发呢!

发表评论


QQ群互动

Linux系统与内核学习群:194051772

WP建站技术学习交流群:194062106

魔豆之路QR

魔豆的Linux内核之路

魔豆的Linux内核之路

优秀工程师当看优秀书籍

优秀程序员,要看优秀书!

赞助商广告

友荐云推荐