ios 自定义带下划线的tab切换按钮
程序员文章站
2023-12-24 16:29:21
...
1. 创建2个tab栏切换的TabBar
#pragma mark -- 创建顶部Tab切换按钮
- (void)createTopTabBarSegment
{
if(!_segmentLineView)
{
_segmentLineView = [[UIView alloc] initWithFrame:CGRectMake((kDEVICEWIDTH - TOPTABBARWIDTH*2 - 35)/2.0, 20+38, TOPTABBARWIDTH, 2)];
_segmentLineView.backgroundColor = loadColor(@"0093ff");
[self.view addSubview:_segmentLineView];
}
//多少个tab
for (NSInteger i = 0; i < _segmentTitleArray.count; i++)
{
UIButton * segmentButton = [UIButton buttonWithType:UIButtonTypeCustom];
segmentButton.frame = CGRectMake((kDEVICEWIDTH - TOPTABBARWIDTH*2 - 35)/2.0 + TOPTABBARWIDTH*i, 20, TOPTABBARWIDTH, 40);
segmentButton.tag = 9999 + i;
[segmentButton setTitle:[_segmentTitleArray objectAtIndex:i] forState:UIControlStateNormal];
[segmentButton setTitle:[_segmentTitleArray objectAtIndex:i] forState:UIControlStateSelected];
[segmentButton setTitleColor:TFCOLOR_68758E forState:UIControlStateNormal];
[segmentButton setTitleColor:loadColor(@"0093ff") forState:UIControlStateSelected];
segmentButton.titleLabel.font = loadFont(18.f);
[segmentButton addTarget:self action:@selector(didTopTabSelectClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:segmentButton];
if (i == 0)//默认选中第一个tab
{
_selectedTabBtn = segmentButton;
[segmentButton setSelected:YES];
}
}
}
#pragma mark -- 顶部tab选择事件
- (void)didTopTabSelectClick:(UIButton*)sender
{
_segmentLineView.frame = CGRectMake((kDEVICEWIDTH - TOPTABBARWIDTH*2 - 35)/2.0 + TOPTABBARWIDTH * (sender.tag - 9999), 20+38, TOPTABBARWIDTH, 2);
_selectedTabBtn.selected = !_selectedTabBtn.selected;
sender.selected = !sender.selected;
_selectedTabBtn = sender;
if (sender.tag == 9999)
{
self.currentSelectedTabIndex = 0;
}
else if (sender.tag == 10000)
{
self.currentSelectedTabIndex = 1;
}}
//清除顶部的tabBar UI上的数据
- (void)clearTopTabBarSegment
{ //先将顶部的View移除掉,再去添加
UIButton *ljBtn = (UIButton*)[self.view viewWithTag:9999];
if (ljBtn) { [ljBtn removeFromSuperview]; }
UIButton *ljBtn1 = (UIButton*)[self.view viewWithTag:10000];
if (ljBtn1) { [ljBtn1 removeFromSuperview]; }
if(_segmentLineView) { [_segmentLineView removeFromSuperview]; _segmentLineView = nil; }}
2. 当从第一个页面里面的某一个button切换到第二个tab时,可以这样处理
#pragma mark -- 查看按钮点击
- (void)aroundClicked
{
CHDebugLog(@"%s",__FUNCTION__);
if (_selectedTabBtn.tag == 9999)
{
if ([self respondsToSelector:@selector(didTopTabSelectClick:)])
{
UIButton *ljBtn1 = (UIButton*)[self.view viewWithTag:10000];//将当前页面里面的第二个tab找到传过去
[self performSelector:@selector(didTopTabSelectClick:) withObject:ljBtn1];
}
}
}
推荐阅读