自定义工具栏tabbar图片
Posted pengyuan_D
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义工具栏tabbar图片相关的知识,希望对你有一定的参考价值。
在AppDelegate.m中,设置根视图控制器
RootViewController.h
@interface RootViewController : UITabBarController
UIImageView *_selectedImg;
RootViewController.m
#import "RootViewController.h"
#import "HomeViewController.h"
#import "SquleViewController.h"
#import "SearchViewController.h"
#import "CommentViewController.h"
#import "MessageViewController.h"
@interface RootViewController ()
@end
@implementation RootViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
// Custom initialization
return self;
- (void)viewDidLoad
[super viewDidLoad];
//隐藏工具栏
[self.tabBar setHidden:YES];
//创建控制器
[self _initViewCtrls];
//<span style="color:#cc0000;">自定义工具栏tabbar</span>
[self _initTabbarView];
//创建控制器
- (void)_initViewCtrls
//创建视图控制器
HomeViewController *homeCtrl =[[HomeViewController alloc] init];
SquleViewController *squleCtrl = [[SquleViewController alloc] init];
SearchViewController *searchCtrl = [[SearchViewController alloc] init];
CommentViewController *commentCtrl = [[CommentViewController alloc] init];
MessageViewController *messageCtrl = [[MessageViewController alloc] init];
//将视图控制器存放到数组中
NSArray *viewCtrls = @[homeCtrl,squleCtrl,searchCtrl,commentCtrl,messageCtrl];
//将视图控制器交给标签控制器管理
self.viewControllers = viewCtrls;
//自定义工具栏tabbar
- (void)_initTabbarView
//创建tabbar的工具栏视图
UIView *tabbarView = [[UIView alloc] initWithFrame:CGRectMake(0, 480-49, 320, 49)];
//设置工具栏的背景图片
tabbarView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"navbg"]];
[self.view addSubview:tabbarView];
//循环创建5个按钮
for (int i=0; i<5; i++)
NSString *name = [NSString stringWithFormat:@"%d",i+1];
//创建按钮
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.tag = i;
//设置按钮的图片
[button setImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
//设置frame值
button.frame = CGRectMake((64-42)/2+64*i, (49-44)/2, 42, 44);
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[tabbarView addSubview:button];
//创建选中图片
_selectedImg = [[UIImageView alloc] initWithFrame:CGRectMake((64-53)/2, (49-45)/2, 53, 45)];
_selectedImg.image = [UIImage imageNamed:@"选中"];
[tabbarView addSubview:_selectedImg];
//按钮点击事件
- (void)buttonAction:(UIButton *) button
//切换视图控制器
self.selectedIndex = button.tag;
[UIView beginAnimations:NULL context:NULL];
[UIView setAnimationDuration:.3];
_selectedImg.center = button.center;
[UIView commitAnimations];
@end
以上是关于自定义工具栏tabbar图片的主要内容,如果未能解决你的问题,请参考以下文章