如何对UITabBarController进行子类化并替换其UITabBar视图?

3
我需要创建一个UITabBarController的子类,以便完全替换UITabBar视图为一个自定义视图,希望可以在界面构建器中实现。我尝试过了但没有成功。
首先,我创建了一个UITabBarController的子类和一个xib文件。我删除了xib文件中的默认视图,并用一个新的视图替换它,该视图只有60像素高(我的标签栏大小)。我将必要的按钮拖到上面,并配置.h文件如下:
@interface ToolbarViewController : UITabBarController

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

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

@end

我的xib长这样:

标签栏xib的Xcode截图

当我启动应用程序时,我看到底部留出了一个空白空间以容纳标签栏,但实际上我没有看到标签栏:

运行时标签栏的应用程序截图

更新:我意识到我实际上没有在.m文件中启动xib文件。有人知道我该如何正确地做这件事吗?


你是否为视图和按钮添加了正确的约束条件? - rdelmar
这不是我的问题。我刚刚意识到我需要在我的viewDidLoad方法中以某种方式添加xib视图。我只是不确定如何正确地做这件事。 - Sam D20
1个回答

5
有不同的解决方案可以将自定义按钮集添加到自定义选项卡栏控制器子类中。多年前,我按照此指南进行了操作:http://idevrecipes.com/2010/12/16/raised-center-tab-bar-button/
其思路是在UITabBarController子类的选项卡栏上添加自定义UIView。CustomTabBarController类不需要拥有xib文件。相反,我有一个UIView的子类,可以通过编程或使用UIView的xib创建。以下是我的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等,或者在视图的初始化程序中以编程方式完成。请注意,这是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。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接