有多种不同的解决方案可以将一组自定义按钮添加到自定义标签栏控制器子类。几年前我按照本指南完成了它:http://idevrecipes.com/2010/12/16/raised-center-tab-bar-button/。
这个想法是在您的 UITabBarController 子类的标签栏上添加一个自定义 UIView。 CustomTabBarController 类不必有 xib。相反,我有一个 UIView 的子类,它可以以编程方式布局,也可以使用 xib 为 UIView 创建。这是我的 CustomTabBarView 类的头文件:
@interface CustomTabBarView : UIView
{
CALayer *opaqueBackground;
UIImageView *tabBG;
IBOutlet UIButton *button0;
IBOutlet UIButton *button1;
IBOutlet UIButton *button2;
NSArray *tabButtons;
int lastTab;
}
@property (nonatomic, weak) id delegate;
-(IBAction)didClickButton:(id)sender;
您可以将所需的按钮连接到 xib 文件中的 button0、button1、button2 等,或者在视图的 init 上以编程方式进行。请注意,这是 UIView 子类。
在 CustomTabBarView.m 中:
-(IBAction)didClickButton:(id)sender {
int pos = ((UIButton *)sender).tag;
// or some other way to figure out which tab button was pressed
[self.delegate setSelectedIndex:pos]; // switch to the correct view
}
然后在您的 CustomTabBarController 类中:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
tabView = [[CustomTabBarView alloc] init];
tabView.delegate = self;
tabView.frame = CGRectMake(0, self.view.frame.size.height-60, 320, 60);
[self.view addSubview:tabView];
}
当在 CustomTabBarView 中单击按钮时,它将调用其委托函数,在本例中为 CustomTabBarController。该调用与单击实际选项卡栏中的选项卡按钮的功能相同,因此如果您像普通的 UITabBarController 一样正确设置了 CustomTabBarController,它将跳转到选项卡。
哦,稍微单独说明一下,添加自定义 xib 作为 UIView 子类的接口的正确方法:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil];
UIView *mainView = [subviewArray objectAtIndex:0];
//Just in case the size is different (you may or may not want this)
mainView.frame = self.bounds;
[self addSubview:mainView];
}
return self;
}
在 xib 文件中,确保 File's Owner 将其自定义类设置为 CustomTabBarView。