// #import "STSegView.h" @interface STSegView() { NSMutableArray* btns; UIView *bar; } @end @implementation STSegView -(instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { _colorNormal = subTitleColor; _colorSelected = defGreen; _barColor = defGreen; _font = 14; btns = [NSMutableArray array]; [self addSelfViewWithRect:CGRectMake(0, self.height, self.width, 1) Color:KlineColor]; bar = [[UIView alloc] initWithFrame:CGRectMake(0, self.height-2, self.width, 3)]; [self addSubview:bar]; } return self; } -(void)setTitles:(NSArray *)titles { if (!titles) { return; } UIButton* btn; /**这里只需要保证。btn的数量足够即可。 */ NSInteger tag = btns.count; for (int i=0; i<(titles.count - _titles.count); i++) { btn = [[UIButton alloc] init]; [self addSubview:btn]; [btns addObject:btn]; [btn target:self]; [btn setTag:tag++]; } bar.width = self.width / titles.count; _titles = titles; } -(void)layoutSubviews { [super layoutSubviews]; if (!_titles) { return; } [bar setBackgroundColor:_barColor]; CGFloat y,w,h; w = self.width * 1.0 / _titles.count; h = self.height; y = 0; UIButton* btn; for (int i =0; i < _titles.count; i++) { btn = btns[i]; [btn setFrame:CGRectMake(w*i, y, w, h)]; [btn setTitleNormal:_titles[i]]; [btn setTitle:_titles[i] textColor:_colorNormal font:_font fotState:UIControlStateNormal]; [btn setTitleColor:_colorSelected forState:UIControlStateSelected]; } } -(void)click:(MyBlockType)block { clkBlock = block; } -(void)setSelectedIndex:(NSInteger)selectedIndex { if (selectedIndex > _titles.count -1) { selectedIndex = _titles.count -1; } if (selectedIndex < 0 ) { selectedIndex = 0; } _selectedIndex = selectedIndex; if (clkBlock) { clkBlock([NSString stringWithFormat:@"%d",(int)selectedIndex]); }else if ([_delegate respondsToSelector:@selector(didSelectedIndex:)]) { [_delegate didSelectedIndex:selectedIndex]; } if (!_titles || _titles.count < 1) { return; } UIButton* btn ; for (btn in btns) { [btn setSelected:NO]; } btn = btns[selectedIndex]; [btn setSelected:YES]; [UIView animateWithDuration:.15 animations:^{ bar.x = selectedIndex * bar.width; }]; } -(void)btnClick:(UIButton*)sender { int tag = (int)sender.tag; self.selectedIndex = tag; } @end