gpt4 book ai didi

ios - 如何继承 UITabBarController 并替换其 UITabBar View ?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:42:21 26 4
gpt4 key购买 nike

我需要对 UITabBarController 进行子类化,这样我就可以用我希望在界面生成器中生成的自定义 View 完全替换 UITabBar View 。我尝试过但没有成功。

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

@interface ToolbarViewController : UITabBarController

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

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

@end

我的 xib 看起来像这样:

Xcode screenshot of the tabbar xib

当我启动应用程序时,我看到底部有一个空白区域用于标签栏,但我没有看到实际的标签栏:

App screenshot of the tabbar at runtime

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

最佳答案

有多种不同的解决方案可以将自定义按钮集添加到自定义选项卡栏 Controller 子类。我几年前就按照本指南完成了: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 等,或者在 View 的 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 中单击按钮时,它将调用其委托(delegate)函数,在本例中为 CustomTabBarController。该调用的功能与单击实际选项卡栏中的选项卡按钮相同,因此如果您像普通 UITabBarController 一样正确设置了 CustomTabBarController,它将跳转到选项卡。

哦,稍微单独说明一下,将自定义 xib 添加为 UIView 子类的接口(interface)的正确方法:

- (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。

关于ios - 如何继承 UITabBarController 并替换其 UITabBar View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25919509/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com