STSegView.m 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. //
  2. #import "STSegView.h"
  3. @interface STSegView()
  4. {
  5. NSMutableArray* btns;
  6. UIView *bar;
  7. }
  8. @end
  9. @implementation STSegView
  10. -(instancetype)initWithFrame:(CGRect)frame
  11. {
  12. self = [super initWithFrame:frame];
  13. if (self) {
  14. _colorNormal = contentTextColor;
  15. _colorSelected = defGreen;
  16. _barColor = defGreen;
  17. _font = 14;
  18. btns = [NSMutableArray array];
  19. [self addSelfViewWithRect:CGRectMake(0, self.height, self.width, 1) ];
  20. bar = [[UIView alloc] initWithFrame:CGRectMake(0, self.height-2, self.width, 3)];
  21. [self addSubview:bar];
  22. }
  23. return self;
  24. }
  25. -(void)setTitles:(NSArray *)titles
  26. {
  27. if (!titles) {
  28. return;
  29. }
  30. UIButton* btn;
  31. /**这里只需要保证。btn的数量足够即可。
  32. */
  33. NSInteger tag = btns.count;
  34. for (int i=0; i<(titles.count - _titles.count); i++) {
  35. btn = [[UIButton alloc] init];
  36. [self addSubview:btn];
  37. [btns addObject:btn];
  38. [btn target:self];
  39. [btn setTag:tag++];
  40. }
  41. bar.width = self.width / titles.count;
  42. _titles = titles;
  43. }
  44. -(void)click:(MyBlockType)block
  45. {
  46. clkBlock = block;
  47. }
  48. -(void)layoutSubviews
  49. {
  50. [super layoutSubviews];
  51. if (!_titles) {
  52. return;
  53. }
  54. [bar setBackgroundColor:_barColor];
  55. CGFloat y,w,h;
  56. w = self.width * 1.0 / _titles.count;
  57. h = self.height;
  58. y = 0;
  59. UIButton* btn;
  60. for (int i =0; i < _titles.count; i++) {
  61. btn = btns[i];
  62. [btn setFrame:CGRectMake(w*i, y, w, h)];
  63. [btn setTitle:_titles[i] forState:UIControlStateNormal];
  64. [btn setTitle:_titles[i] textColor:_colorNormal font:_font fotState:UIControlStateNormal];
  65. [btn setTitleColor:_colorSelected forState:UIControlStateSelected];
  66. }
  67. }
  68. -(void)setSelectedIndex:(NSInteger)selectedIndex
  69. {
  70. if (selectedIndex > _titles.count -1) {
  71. selectedIndex = _titles.count -1;
  72. }
  73. if (selectedIndex < 0 ) {
  74. selectedIndex = 0;
  75. }
  76. _selectedIndex = selectedIndex;
  77. if (clkBlock) {
  78. clkBlock([NSString stringWithFormat:@"%d",(int)selectedIndex]);
  79. }
  80. if (!_titles || _titles.count < 1) {
  81. return;
  82. }
  83. UIButton* btn ;
  84. for (btn in btns) {
  85. [btn setSelected:NO];
  86. }
  87. btn = btns[selectedIndex];
  88. [btn setSelected:YES];
  89. [UIView animateWithDuration:.15 animations:^{
  90. bar.x = selectedIndex * bar.width;
  91. }];
  92. }
  93. -(void)btnClick:(UIButton*)sender
  94. {
  95. int tag = (int)sender.tag;
  96. self.selectedIndex = tag;
  97. }
  98. @end