通过代码创建UITabBar,并添加TabBarItem new

现在,打开Xcode,创建Single还是Empty application就随便你了。现在有这两种方式,第一种在AppDelegate中创建,还有一种就是自己创建一个ViewController在里面建立TabBar。这里说一下在AppDelegate中创建,至于另外一种只需要改几句代码就行了。

经过自己的测试发现,如果你不在AppDelegate中写的,而且AppDelegate中用navigationbar作为程序主框架,那么可能会造成冲突。因为navigationbar和tabbar不可能创建两个window放在里面。我就这样写然后造成了TabBar中的子视图中的TableView无法加载点击事件,悲催,不过好在我已找到解决方法,静待下一篇文章后续⋯⋯

创建好程序后,在AppDelegate.h中声明一下UITabBarController *tabBar,然后@property和@synthesize,在applicationDidFinishLauching中书写代码即可,具体如下:

//在AppDelegate.h文件中
@interface AppDelegate : UIResponder
{
   UITabBarController *tabBar;
}

@property (strong, nonatomic) UIWindow *window;
@property (retain, nonatomic) IBOutlet UITabBarController *tabBar;

@end

//在AppDelegate.m文件中
@implementation AppDelegate

@synthesize window = _window;
@synthesize tabBar;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    self.window.backgroundColor = [UIColor whiteColor];

    tabBar = [[UITabBarController alloc]init];
    UIOneViewController *one = [[UIOneViewController alloc]init];
    UITwoViewController *Two = [[UITwoViewController alloc]init];
    tabBar.viewControllers = [NSArray arrayWithObjects:one,two,nil];

    [one release];
    [two release];
    //如果不在AppDelegate里创建,则在ViewDidLoad里写,将下面的window改成view
    [self.window addSubview:self.tabBar.view];

    [tabBar release];

    [self.window makeKeyAndVisible];
    return YES;
}

至此运行你就能看到在iPhone模拟器的下方会出现有两个空的TabBarItem的TabBar界面。下一步工作就要添加TabBarItem按钮了,按照上述的代码,我们有两个ViewController,分别叫UIOneViewController和UITwoViewController,要将两者作为item添加到TabBar中去,下面的代码在UIOneViewController.m里面书写。

//重写UIOneViewController里面的init和initWithNibName方法
- (id)init
{
    self = [super initWithNibName:nil bundle:nil];
    if (self)
    {
        UITabBarItem *OneItem = [self tabBarItem];
        UIImage *OneImage = [UIImage imageNamed:@"tabBar1.png"];
        OneItem.image = OneImage;
        OneItem.title = @"Just For Test";
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    return self.init;
}

然后在UITwoViewController.m里面写上类似于上面的方法,运行即可看到效果,我这里就不贴效果图了。

如果想在TabBar后面添加自定义背景图片的话,可以通过下面的代码,加到application didFinishLauchingWithOptions或者是ViewDidLoad中,不过貌似是只有iOS 5才可以:

UIImage *tabBarImage = [UIImage imageNamed:@"TabBar.png"];
[[tabBarController tabBar]setBackgroundImage:tabBarImage];

如果是iOS 5之前的版本,添加下面代码(我只在iOS 5的模拟器中试验过):

@implementation UITabBar (TabBarCustom)

- (void)drawRect:(CGRect)rect
{
    UIImage *image = [UIImage imageNamed:@"TabBar.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}

@end

 

转自http://xiaoyu.li/2012/creat-uitabbar-by-code/ 用于学习和交流,版权归原主人所有

posted @ 2012-08-07 15:42  陪上帝流浪c2di  阅读(621)  评论(0编辑  收藏  举报