2014-09-18 90 views
2

我需要子类UITabBarController,以便我可以用自定义视图完全替换UITabBar视图,我希望可以在界面生成器中生成该视图。我试过但没有成功。如何继承UITabBarController并替换它的UITabBar视图?

首先,我创建了一个UITabBarController的子类以及一个xib。我删除了xib中的默认视图,并将其替换为只有60px高(我的tabbar的大小)的新视图。我拖着必要的按钮到它,并配置了.h文件中像这样:

@interface ToolbarViewController : UITabBarController 

@property (strong, nonatomic) IBOutlet UIView *tabBarView; 

@property (strong, nonatomic) IBOutlet UIButton* firstButton; 
@property (strong, nonatomic) IBOutlet UIButton* secondButton; 

@end 

我的厦门国际银行是这样的:

enter image description here

当我启动的应用程序,我看到一个空的空间在底部的标签栏做,但我没有看到实际的标签栏:

enter image description here

更新:我知道,我实际上并没有实际启动.m文件中的xib文件。任何人都知道我可以如何做到这一点?

+0

您是否为视图和按钮添加了适当的约束条件? – rdelmar 2014-09-18 18:10:35

+0

这不是我的问题。我刚刚意识到我需要在我的viewDidLoad方法中以某种方式添加xib视图。我只是不确定如何正确执行此操作。 – 2014-09-18 18:16:24

回答

4

将自定义按钮组添加到自定义选项卡栏控制器子类中有多种不同的解决方案。按照本指南,我几年前就已经完成了它: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; 

你要么连接所需的按钮BUTTON0,按钮1,按钮2,等在厦门国际银行文件,或做编程上的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,它将跳转到选项卡。

哦,在一个稍微不同的音符,正确的方法来添加自定义厦门国际银行作为接口的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文件,确保文件的所有者拥有自定义类设置为CustomTabBarView。