向标签栏添加自定义中心按钮的最佳方法是什么?

时间:2011-09-23 09:55:10

标签: iphone objective-c ios uitabbarcontroller uitabbar

许多应用都有一个标准的标签栏,中间有一个自定义按钮,可以执行一些特殊功能。可以在这里找到一些例子:

http://mobile-patterns.com/custom-tab-navigation

实现这个目标的最佳方式是什么?

2 个答案:

答案 0 :(得分:11)

Here您可以看到如何实现该按钮。我将粘贴代码,以便它永远留在这里:

UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
[button setBackgroundImage:buttonImage forState:UIControlStateNormal];
[button setBackgroundImage:highlightImage forState:UIControlStateHighlighted];

CGFloat heightDifference = buttonImage.size.height - self.tabBar.frame.size.height;
if (heightDifference < 0)
    button.center = self.tabBar.center;
else
{
    CGPoint center = self.tabBar.center;
    center.y = center.y - heightDifference/2.0;
    button.center = center;
}

[self.view addSubview:button];

希望有所帮助

答案 1 :(得分:8)

我让Franciso的代码进行了一些小调整。我将代码放在Xcode 4.1中标准Tab Bar应用程序模板的应用程序didFinishLaunchingWithOptions方法中。我相信Xcode 4.2可能有不同的模板。

UIImage *buttonImage = [UIImage imageNamed:@"tabItemOff.png"];
UIImage *highlightImage = [UIImage imageNamed:@"tabItemSelected.png"];
UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
[button setBackgroundImage:buttonImage forState:UIControlStateNormal];
[button setBackgroundImage:highlightImage forState:UIControlStateHighlighted];
CGFloat heightDifference = buttonImage.size.height - self.tabBarController.tabBar.frame.size.height;
if (heightDifference < 0)
    button.center = self.tabBarController.tabBar.center;
else
{
    CGPoint center = self.tabBarController.tabBar.center;
    center.y = center.y - heightDifference/2.0;
    button.center = center;
}
[self.tabBarController.view addSubview:button];