#define kSignalH 2 //下标高度
#import "SASwitchBar.h"
@interface
SASwitchBar()
{
UIScrollView *_scrollView;
UIView *_signal;
UIButton *_selectedItem;
}
@end
@implementation
SASwitchBar
#pragma mark - 初始化方法
- (
void
)initialize
{
_signal = [[UIView alloc] init];
_scrollView = [[UIScrollView alloc] init];
[
self
addSubview:_scrollView];
[_scrollView addSubview:_signal];
}
- (instancetype)initWithCoder:(
NSCoder
*)aDecoder
{
if
(
self
= [
super
initWithCoder:aDecoder]) {
[
self
initialize];
}
return
self
;
}
- (instancetype)init
{
if
(
self
= [
super
init]) {
[
self
initialize];
}
return
self
;
}
- (instancetype)initWithItems:(
NSArray
*)items
{
if
(
self
= [
super
init]) {
[
self
initialize];
[
self
setItems:items];
}
return
self
;
}
- (
void
)layoutSubviews
{
_scrollView.frame = (CGRect){CGPointZero,
self
.frame.size};
NSInteger
items =
self
.items.count;
CGFloat btnW =
self
.frame.size.width / items;
CGFloat btnH =
self
.frame.size.height - kSignalH;
for
(
int
i = 0; i < items; i ++) {
UIButton *btn =
self
.items[i];
btn.frame = CGRectMake(i * btnW, 0, btnW, btnH);
}
_signal.frame = CGRectMake(0, btnH, btnW, kSignalH);
}
#pragma mark - 成员属性设置
- (
void
)setItems:(
NSArray
*)items
{
NSMutableArray
*array = [
NSMutableArray
array];
for
(
int
i = 0; i < items.count; i++) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.tag = i + 1;
[array addObject:btn];
[btn setTitle:items[i] forState:UIControlStateNormal];
btn.titleLabel.font = [UIFont boldSystemFontOfSize:15];
[btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[btn addTarget:
self
action:
@selector
(switchItem:) forControlEvents:UIControlEventTouchUpInside];
[_scrollView addSubview:btn];
}
_items = [
NSArray
arrayWithArray:array];
self
.selColor = [UIColor orangeColor];
self
.selectedIndex = 0;;
}
- (
void
)setSelectedIndex:(
NSInteger
)selectedIndex
{
_selectedIndex = selectedIndex;
[
self
switchItem:
self
.items[selectedIndex]];
}
- (
void
)setSelColor:(UIColor *)selColor
{
_selColor = selColor;
_signal.backgroundColor = selColor;
for
(UIButton *btn in
self
.items) {
[btn setTitleColor:selColor forState:UIControlStateSelected];
}
}
#pragma mark - 事件处理
- (
void
)switchItem:(UIButton *)button
{
_selectedItem.selected =
NO
;
_selectedItem = button;
button.selected =
YES
;
CGRect rect = button.frame;
CGFloat x = rect.origin.x;
CGFloat y = rect.origin.y + rect.size.height;
CGFloat w = rect.size.width;
CGFloat h = rect.size.height;
[UIView animateWithDuration:0.3 animations:^{
_signal.frame = CGRectMake(x, y, w, h);
}];
if
([
self
.delegate respondsToSelector:
@selector
(switchBar:seletedIndex:)]) {
[
self
.delegate switchBar:
self
seletedIndex:button.tag];
}
}
@end