关于UIButton和UITabBar的问题

时间:2011-07-25 04:42:09

标签: iphone objective-c uibutton uitabbarcontroller

我正在尝试在UITabBar上面放置一个带有图像的UIButton。

我在applicationDidFinishLaunching方法中添加了这段代码,但是我发现了一些错误,tabBar无法识别。

我在IB中构建了TabBarController和NavController。

UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *buttonImage = [UIImage imageNamed:@"addTabButton.png"];
UIImage *highlightImage = [UIImage imageNamed:@"addTabButtonHighlight.png"];
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];

编辑:

UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *buttonImage = [UIImage imageNamed:@"addTabButton.png"];
UIImage *highlightImage = [UIImage imageNamed:@"addTabButtonHighlight.png"];
button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
[button setBackgroundImage:buttonImage forState:UIControlStateNormal];
[button setBackgroundImage:highlightImage forState:UIControlStateHighlighted];
[button addTarget:self action:@selector(btnTouchUpInside:) forControlEvents:UIControlEventTouchUpInside]; 
[self.window addSubview:button];

3 个答案:

答案 0 :(得分:0)

您可以在.h文件中发布出口和属性的代码吗? 你有可能在主ViewController中制作它们吗?因为applicationDidFinishLaunching是一个appDelegate方法,你通常不应该在那里做UI事情,只是在viewControllers中。

答案 1 :(得分:0)

applicationDidFinishLaunching不适合放置这样的方法。改为使用viewDidLoad或viewWillAppear。

答案 2 :(得分:0)

您似乎正在关注此博文http://idevrecipes.com/2010/12/16/raised-center-tab-bar-button/来创建自定义TabBar,但您没有正确关注它。您正在做的是将按钮作为子视图添加到普通viewController的视图,同时您需要将按钮添加到TabBar的视图。当tabBarContoller要显示时,尝试添加按钮。就像你从mainWindow中删除导航控制器的视图并添加tabBarController的视图那样然后在将tabBarController的视图添加到窗口之前将你的按钮添加到tabBarController的tabBar.view,这样你的代码就会是这样的

[tabBarController.tabBar.view addSubview:yourButton]; 
[window addSubView:tabBarController.view];

试着让我知道你得到了什么......