123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161 |
- //
- #import "STSegView.h"
- #define lineColor [UIColor colorWithWhite:.3 alpha:.1]
- #define subTitleColor [UIColor colorWithWhite:.3 alpha:1]
- @interface STSegView()
- {
- NSMutableArray* btns;
-
- UIView *bar;
- }
- @end
- @implementation STSegView
- -(instancetype)initWithFrame:(CGRect)frame
- {
- self = [super initWithFrame:frame];
- if (self) {
- _colorNormal = subTitleColor;
- _colorSelected = RQMianColor;
- _barColor = RQMianColor;
- _font = 14;
-
- btns = [NSMutableArray array];
-
- [self addSelfViewWithRect:CGRectMake(0, self.height, self.width, 1) Color:lineColor];
-
- 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
|