【标签条】 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
效果图: