What's the best way of adding a custom centre button to a tab bar?

北城余情 提交于 2019-12-07 10:47:38

问题


Many apps have a standard tab bar with a custom button in the centre which performs some special function. Some examples can be found here:

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

What's the best way of implementing this?


回答1:


Here you can see how to implement that button. I am gonna paste the code so it stays here forever:

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];

Hope it helps




回答2:


I got Franciso's code working with a few minor tweaks. I placed the code in the application didFinishLaunchingWithOptions method of a standard Tab Bar Application template in Xcode 4.1. I believe Xcode 4.2 may have a different template.

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];


来源:https://stackoverflow.com/questions/7527192/whats-the-best-way-of-adding-a-custom-centre-button-to-a-tab-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!