核心代码如下:
效果图如下:
[img]
[img]http://dl.iteye.com/upload/attachment/0078/7480/fb01c512-4529-3d7c-8caa-431a6df282c5.png[/img]
[/img]
- (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];
}效果图如下:
[img]
[img]http://dl.iteye.com/upload/attachment/0078/7480/fb01c512-4529-3d7c-8caa-431a6df282c5.png[/img]
[/img]
本文介绍如何在 iOS 应用的 TabBar 中间添加一个自定义按钮,并详细展示了实现这一功能的具体步骤与核心代码。通过调整按钮的位置使其适配 TabBar 的高度,实现了美观且实用的功能。
14

被折叠的 条评论
为什么被折叠?



