标题按钮下添加下滑线
- 获得按钮内部文字尺寸有两种方法:
方法一:
- 根据计算按钮内部文字的尺寸, 设置下滑线的宽度,
- 在根据选中的是哪个按钮, 并设置下划线的位置中心点就在对应按钮的中心线上;
self.titleUnderline.CDH_width = [titleButton.currentTitle sizeWithFont:titleButton.titleLabel.font].width; self.titleUnderline.CDH_width = [titleButton.currentTitle sizeWithAttributes:@{NSFontAttributeName : titleButton.titleLabel.font}].width;方法二:
- 直接获取 按钮内部的 Label 的尺寸设置下划线的宽度即可;
self.titleUnderline.CDH_width = titleButton.titleLabel.CDH_width + 10; self.titleUnderline.CDH_centerX = titleButton.CDH_centerX;程序一进来就默认点击第一个按钮
- 注意点: 一定要先调用 sizeToFit 方法计算出 按钮内部 titleLabel 的尺寸, 给下滑线的宽度赋值, 如果没调用 sizeToFit 这个方法计算 按钮内部的 titleLabel 的尺寸, 则一开始的时候默认是没有尺寸的.
// 设置按钮下的下滑线
- (void)setUpTitleUnderline{
CDHTitleButton *firstTitleButton = _titlesView.subviews[0];
UIView *titleUnderline = [[UIView alloc] init];
titleUnderline.backgroundColor = [firstTitleButton titleColorForState:UIControlStateSelected];
_titleUnderline = titleUnderline;
CGFloat titleUnderlineH = 2;
CGFloat titleUnderlineY = _titlesView.CDH_height - titleUnderlineH;
titleUnderline.frame = CGRectMake(0, titleUnderlineY, 0 , titleUnderlineH);
[_titlesView addSubview:titleUnderline];
// 这里一定要调用 sizeToFit 的方法计算出按钮内部的Label 的尺寸
[firstTitleButton.titleLabel sizeToFit];
[self clickTitleButton:firstTitleButton];
// // 新点击的按钮 -> 红色
// firstTitleButton.selected = YES;
// _previousClickTitleButton = firstTitleButton;
//
// // 下划线
// [firstTitleButton.titleLabel sizeToFit];
// self.titleUnderline.CDH_width = firstTitleButton.titleLabel.CDH_width + 10;
// self.titleUnderline.CDH_centerX = firstTitleButton.CDH_centerX;
}
#pragma mark - 监听按钮点击事件
// 监听按钮点击事件
- (void)clickTitleButton:(UIButton *)titleButton{
_previousClickTitleButton.selected = NO;
// 取消上一个的自控制的 view 点击状态栏回顶功能
UIScrollView *ChildView = (UIScrollView *)self.childViewControllers[_previousClickTitleButton.tag].view;
ChildView.scrollsToTop = NO;
titleButton.selected = !titleButton.selected;
_previousClickTitleButton = titleButton;
// 在这里添加对应的控制 View 到 scrollView 中
[self addChildViewToScrollView:titleButton.tag];
ChildView = (UIScrollView *)self.childViewControllers[_previousClickTitleButton.tag].view;
ChildView.scrollsToTop = YES;
// 修改偏移量
CGPoint Offset = _scrollView.contentOffset;
Offset.x = titleButton.tag * _scrollView.CDH_width;
[UIView animateWithDuration:0.3 animations:^{
_titleUnderline.CDH_width = titleButton.titleLabel.CDH_width + 10;
_titleUnderline.CDH_centerX = titleButton.CDH_centerX;
_scrollView.contentOffset = Offset;
} completion:^(BOOL finished) {
}];
}