iOS开发-自定义tabbar

实现重写TabBar的TabBarItem,然后在中间额外加一个按钮。

.h文件

#import2

 @interface WPTabBar : UITabBar

 @end

.m文件

#import "WPTabBar.h"

@interface WPTabBar ()

//@property (nonatomic,weak)UIButton *centerButton;

@end

@implementation WPTabBar

- (void)layoutSubviews

{

[super layoutSubviews];

UIButton *centerButton = [UIButton buttonWithType:UIButtonTypeCustom];

[centerButton setImage:[UIImage imageNamed:@"tab_bar_ride0"] forState:UIControlStateNormal];

[centerButton setImage:[UIImage imageNamed:@"tab_bar_ride1"] forState:UIControlStateHighlighted];

// 一定要记得设置尺寸

[centerButton sizeToFit];

[self addSubview:centerButton];

// 获取子按钮总数

NSInteger count = self.items.count;

CGFloat x = 0;

CGFloat y = 0;

CGFloat w = self.width / (count + 1);

CGFloat h = self.height;

int i = 0;

// 遍历所有的tabBarButton

for (UIControl *tabBarButton in self.subviews) {

if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {

if (i == 2) {

i += 1;

}

x = i * w;

//  设置UITabBarButton位置

tabBarButton.frame = CGRectMake(x, y, w, h);

tabBarButton.tag = i;

i++;

// 监听 UIControlEventTouchDownRepeat : 短时间内连续地重复点击

//            [tabBarButton addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchDownRepeat];

[tabBarButton addTarget:self action:@selector(centerButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

}

}

// 设置加号按钮位置

centerButton.center = CGPointMake(UIScreenWidth * 0.5, h * 0.5);

}

- (void)centerButtonClicked:(UIButton*)sender{

//可以在这里实现想要的操作,或者添加委托方法,让代理去实现

}

@end

在工程的tabbarController的viewDidLoad方法中实现自定义tabbar替换系统的tabbar,并且实现自定义tabbar的代理方法:

WPTabBar *tabBar = [[WPTabBar alloc] init];

// 设置代理

tabBar.delegate = self;

// KVC:如果要修系统的某些属性,但被设为readOnly,就是用KVC,即setValue:forKey:。

// 修改tabBar为自定义tabBar

[self setValue:tabBar forKey:@"tabBar"];

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容