// // CommonTabBar.m // HC // // Created by huilinLi on 2025/11/25. // #import "CommonTabBar.h" @interface CommonTabBar () @property (nonatomic, strong) NSArray *tabButtons; @end @implementation CommonTabBar - (instancetype)initWithTabItems:(NSArray *)tabItems { self = [super init]; if (self) { self.backgroundColor = [UIColor blackColor]; self.translatesAutoresizingMaskIntoConstraints = NO; [self setupTabButtonsWithItems:tabItems]; } return self; } - (void)setupTabButtonsWithItems:(NSArray *)tabItems { NSMutableArray *buttons = [NSMutableArray array]; for (NSInteger i = 0; i < tabItems.count; i++) { NSDictionary *item = tabItems[i]; UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem]; UIButtonConfiguration *config = [UIButtonConfiguration plainButtonConfiguration]; config.image = [UIImage systemImageNamed:item[@"icon"] ?: @""]; config.title = item[@"title"]; config.imagePlacement = NSDirectionalRectEdgeTop; config.imagePadding = 5; btn.configuration = config; BOOL selected = [item[@"selected"] boolValue]; btn.tintColor = selected ? [UIColor blueColor] : [UIColor whiteColor]; btn.titleLabel.font = [UIFont systemFontOfSize:10]; btn.tag = i; [btn addTarget:self action:@selector(tabButtonTapped:) forControlEvents:UIControlEventTouchUpInside]; [self addSubview:btn]; [buttons addObject:btn]; } self.tabButtons = buttons; [self setupTabButtonConstraints]; } - (void)setupTabButtonConstraints { for (NSInteger i = 0; i < self.tabButtons.count; i++) { UIButton *btn = self.tabButtons[i]; btn.translatesAutoresizingMaskIntoConstraints = NO; [NSLayoutConstraint activateConstraints:@[ [btn.widthAnchor constraintEqualToAnchor:self.widthAnchor multiplier:1.0/self.tabButtons.count], [btn.heightAnchor constraintEqualToAnchor:self.heightAnchor], [btn.centerYAnchor constraintEqualToAnchor:self.centerYAnchor], (i == 0) ? [btn.leadingAnchor constraintEqualToAnchor:self.leadingAnchor] : [btn.leadingAnchor constraintEqualToAnchor:self.tabButtons[i-1].trailingAnchor], ]]; } // TabBar自身高度 [self.heightAnchor constraintEqualToConstant:60].active = YES; } - (void)tabButtonTapped:(UIButton *)sender { self.selectedIndex = sender.tag; for (UIButton *btn in self.tabButtons) { btn.tintColor = (btn.tag == sender.tag) ? [UIColor blueColor] : [UIColor whiteColor]; } if ([self.delegate respondsToSelector:@selector(tabBarDidSelectIndex:)]) { [self.delegate tabBarDidSelectIndex:sender.tag]; } } // 外部设置选中索引时更新样式 - (void)setSelectedIndex:(NSInteger)selectedIndex { _selectedIndex = selectedIndex; for (UIButton *btn in self.tabButtons) { btn.tintColor = (btn.tag == selectedIndex) ? [UIColor blueColor] : [UIColor whiteColor]; } } @end