UITabBar 【标签条】自己的见解

本文介绍了如何在iOS应用中使用UITabBar控件。通过创建UITabBar和UITabBarItem对象,设置委托来响应用户选择,实现了自定义标签栏的功能。提供了完整的代码示例。

【标签条】 UITabBar


UITabBar也可以单独使用,就像普通UI控件一样,可以在SB拖控件,也可以代码创建对象。


方法:

 

1 创建一个UITabBar对象

2 创建多个UITabBarItem对象,并将这些UITabBarItem设置给UITabBar对象。

3 为UITabBar对象设置一个UITabBarDelegate对象,用于监听用户的选中信息。


代码:


AppDelegate.h



#import "ViewController.h"


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window=[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    self.window.backgroundColor=[UIColor whiteColor];

    ViewController *viewController=[[ViewController alloc] init];

    self.window.rootViewController=viewController;

    [self.window makeKeyAndVisible];

    return YES;

}



ViewController.h


#import "ViewController.h"


@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad

{

    [super viewDidLoad];


    CGSize viewBounds=self.view.bounds.size;

    //创建UITabBar对象

    UITabBar *tabBar=[[UITabBar alloc] initWithFrame:CGRectMake(0, 20, viewBounds.width, viewBounds.height)];

    tabBar.delegate=self;

    [self.view addSubview:tabBar];

    

    //使用系统图标创建标签项

    UITabBarItem *tabItem1=[[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemHistory tag:0];

    //自定义图标创建

    UITabBarItem *tabItem2=[[UITabBarItem alloc ]initWithTitle:@"首页" image:[UIImage imageNamed:@"icon.png"] tag:1];

    //就是图标右上方会有数字提示的效果

    tabItem2.badgeValue=@"";

    

    //UITabBar设置多个标签项

    tabBar.items=@[tabItem1,tabItem2];

}

//UITabBarDelegate定义的方法,当用户选中某个标签的时候激发该方法。

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item

{

    NSString* msg = [NSString stringWithFormat:@"您选中第【%ld】项"  , item.tag];

    // 创建并显示一个UIAlertView控件

    UIAlertView* alert = [[UIAlertView alloc]

                          initWithTitle:@"提示" message:msg

                          delegate:nil cancelButtonTitle:@"OK"

                          otherButtonTitles: nil];

    [alert show];

}


@end


效果图:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值