2023-04-28 iOS 自定义SegmentControl 能滑动能点击

#import <UIKit/UIKit.h>


@protocol ZJFontSegmentControlDelegate <NSObject>
- (CGFloat)segmentControlTitleSizeForIndex:(NSInteger)index;
@end

@interface ZJFontSegmentControl : UIView

@property (nonatomic, assign) NSInteger selectedSegmentIndex;
@property (nonatomic, strong) UIColor *selectedBgColor;
@property (nonatomic, strong) UIColor *backBgColor;
@property (nonatomic, strong) UIColor *selectedTextColor;
@property (nonatomic, strong) UIColor *normalTextColor;
@property (nonatomic, copy)   void (^selectIndex)(NSInteger index);
@property (nonatomic, weak)   id<ZJFontSegmentControlDelegate> delegate;

- (instancetype)initWithFrame:(CGRect)frame Items:(NSArray<NSString *> *)items;

@end
#import "ZJFontSegmentControl.h"
#import "UIView+Extension.h"


@interface ZJNoHighlightButton : UIButton

@end
@implementation ZJNoHighlightButton
//重写该方法可以去除长按按钮时出现的高亮效果
- (void)setHighlighted:(BOOL)highlighted
{
  
}
@end

@interface ZJFontSegmentControl()

@property (nonatomic, strong) NSArray<NSString *> *items;
@property (nonatomic, strong) NSMutableArray<UIButton*> *segments;
@property (nonatomic, strong) UIView *segmentBackView;
@property (nonatomic, strong) UIButton *segSliderBtn;
@property (nonatomic, strong) UIButton *beforeBtn;
@property (nonatomic, assign) NSInteger defaultSegment;
@property (nonatomic, assign) BOOL canDrag;

@end
@implementation ZJFontSegmentControl


- (instancetype)initWithFrame:(CGRect)frame Items:(NSArray<NSString *> *)items {
  self = [super initWithFrame:frame];
  if (self) {
      self.userInteractionEnabled = true;
      self.backgroundColor = [UIColor clearColor];
      self.items = items;
      self.canDrag = true;
      self.selectedBgColor = [UIColor redColor];
      self.backBgColor = [UIColor yellowColor];
      self.selectedTextColor = [UIColor blueColor];
      self.normalTextColor = [UIColor greenColor];
  }
  return self;
}
#pragma mark-- set
- (void)setSelectedSegmentIndex:(NSInteger)selectedSegmentIndex {
  _defaultSegment = selectedSegmentIndex;
  [self setupUI];
}

- (void)setSelectedBgColor:(UIColor *)selectedBgColor {
  self.segSliderBtn.backgroundColor = selectedBgColor;
}

- (void)setBackBgColor:(UIColor *)backBgColor {
  self.segmentBackView.backgroundColor = backBgColor;
}

- (void)setSelectedTextColor:(UIColor *)selectedTextColor {
  _selectedTextColor = selectedTextColor;
}

- (void)setNormalTextColor:(UIColor *)normalTextColor{
  _normalTextColor = normalTextColor;
}

- (void)restSegmentsSelected {
  if (self.beforeBtn != self.segments[self.defaultSegment]) {
      [self.segments[self.defaultSegment] setSelected:true];
      [self.beforeBtn setSelected:false];
  }
  self.beforeBtn = self.segments[self.defaultSegment];
}

#pragma mark-- UI
- (void)setupUI {

  if (self.segments == nil) {
      //添加滑动手势
      UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGesture:)];
      [self addGestureRecognizer:panGesture];
      
      self.segments = [NSMutableArray array];
      CGFloat btnWidth = self.frame.size.width / self.items.count;
      CGFloat btnHeight = self.frame.size.height;
      //创建tab
      for (int i = 0; i < self.items.count; i++) {
          ZJNoHighlightButton *button = [ZJNoHighlightButton buttonWithType:UIButtonTypeCustom];
          button.frame = CGRectMake(btnWidth * i, 0, btnWidth, btnHeight);
          [button setTitle:[self.items objectAtIndex:i] forState:UIControlStateNormal];
          [button setTitleColor:self.normalTextColor forState:UIControlStateNormal];
          [button setTitleColor:self.selectedTextColor forState:UIControlStateSelected];
          button.titleLabel.font = [UIFont systemFontOfSize:[self sizeForIndex:i]];
          button.layer.cornerRadius = self.frame.size.height / 2;
          button.layer.masksToBounds = true;
          button.userInteractionEnabled = true;
          button.tag = i;
          [button addTarget:self action:@selector(tabAction:) forControlEvents:UIControlEventTouchUpInside];
          button.backgroundColor = [UIColor clearColor];
          [self.segmentBackView addSubview:button];
          [self.segments addObject:button];
      }
  }
  
  if (self.defaultSegment < self.segments.count) {
      self.segSliderBtn.frame = self.segments[self.defaultSegment].frame;
      [self restSegmentsSelected];
  } else {
      NSLog(@"选定段索引超出数组范围");
  }
}

- (UIView *)segmentBackView {
  if (!_segmentBackView) {
      UIView *segmentBackView = [[UIView alloc]initWithFrame:self.bounds];
      segmentBackView.backgroundColor = self.backBgColor;
      segmentBackView.layer.cornerRadius = self.frame.size.height / 2;
      segmentBackView.layer.masksToBounds = true;
      [self addSubview:segmentBackView];
      _segmentBackView = segmentBackView;
  }
  return _segmentBackView;
}

- (UIButton *)segSliderBtn {
  if (!_segSliderBtn) {
      UIButton *segSliderBtn = [UIButton buttonWithType:UIButtonTypeCustom];
      segSliderBtn.layer.cornerRadius = self.frame.size.height / 2;
      segSliderBtn.layer.masksToBounds = true;
      segSliderBtn.backgroundColor = self.selectedBgColor;
      [segSliderBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
      [self.segmentBackView addSubview:segSliderBtn];
      self.segSliderBtn = segSliderBtn;
  }
  return _segSliderBtn;
}

#pragma mark-- Actions
- (void)panGesture:(UIPanGestureRecognizer *)geture {
  @weakify(self);
  CGPoint pointA = [geture locationInView:self.segmentBackView];
  if (geture.state == UIGestureRecognizerStateBegan) {
      if (!CGRectContainsPoint(self.segSliderBtn.frame, pointA)) {
          self.canDrag = false;
          return;
      }
  }
  
  if (geture.state == UIGestureRecognizerStateChanged) {
      if (self.canDrag == false) {
          return;
      }
      //改变滑动button的位置
      for (int i = 0; i < self.items.count; i++ ) {
          UIButton *button = self.segments[i];
          if (pointA.x > button.minX && pointA.x < button.maxX) {
              [UIView animateWithDuration:0.1 animations:^{
                  @strongify(self);
                  self.segSliderBtn.center = self.segments[i].center;
                  self.defaultSegment = i;
                  [self restSegmentsSelected];
              }];
              break;
          }
      }
  }
  
  [geture setTranslation:CGPointZero inView:self.segmentBackView];
  
  if (geture.state == UIGestureRecognizerStateEnded ) {
      self.canDrag = true;
      if (self.selectIndex) {
          self.selectIndex(self.defaultSegment);
      }
  }
}

- (void)tabAction:(UIButton *)sender {
  @weakify(self);
  if (sender.tag == self.defaultSegment) {
      return;
  }
  
  UIButton *button = self.segments[sender.tag];
  [UIView animateWithDuration:0.2 animations:^{
      @strongify(self);
      self.segSliderBtn.center = button.center;
  }];
  self.defaultSegment = sender.tag;
  [self restSegmentsSelected];

  if (self.selectIndex) {
      self.selectIndex(self.defaultSegment);
  }
}

- (CGFloat)sizeForIndex:(NSInteger)index {
  if ([self.delegate respondsToSelector:@selector(segmentControlTitleSizeForIndex:)]) {
      return [self.delegate segmentControlTitleSizeForIndex:index];
  }
  return 15.0;
}

@end

下面为等边等距
#define Width_Space      10.0f      // 2个按钮之间的横间距
#pragma mark-- UI
- (void)setupUI {

  if (self.segments == nil) {
      //添加滑动手势
      UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGesture:)];
      [self addGestureRecognizer:panGesture];
      
      self.segments = [NSMutableArray array];
      CGFloat btnWidth = ((self.frame.size.width  - Width_Space  * (self.items.count + 1 )) / self.items.count);
      CGFloat btnHeight = self.frame.size.height;
      //创建tab
      for (int i = 0; i < self.items.count; i++) {
          ZJNoHighlightButton *button = [ZJNoHighlightButton buttonWithType:UIButtonTypeCustom];
          button.frame = CGRectMake(i * (btnWidth + Width_Space) + Width_Space, 0, btnWidth, btnHeight);
          [button setTitle:[self.items objectAtIndex:i] forState:UIControlStateNormal];
          [button setTitleColor:self.normalTextColor forState:UIControlStateNormal];
          [button setTitleColor:self.selectedTextColor forState:UIControlStateSelected];
          button.titleLabel.font = [UIFont systemFontOfSize:[self sizeForIndex:i]];
          button.layer.cornerRadius = self.frame.size.height / 2;
          button.layer.masksToBounds = true;
          button.userInteractionEnabled = true;
          button.tag = i;
          [button addTarget:self action:@selector(tabAction:) forControlEvents:UIControlEventTouchUpInside];
          button.backgroundColor = [UIColor clearColor];
          [self.segmentBtnBackView addSubview:button];
          [self.segments addObject:button];
      }
  }
  
  if (self.defaultSegment < self.segments.count) {
      self.segSliderBtn.frame = self.segments[self.defaultSegment].frame;
      [self restSegmentsSelected];
  } else {
      NSLog(@"选定段索引超出数组范围");
  }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,056评论 5 474
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,842评论 2 378
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 148,938评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,296评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,292评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,413评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,824评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,493评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,686评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,502评论 2 318
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,553评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,281评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,820评论 3 305
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,873评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,109评论 1 258
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,699评论 2 348
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,257评论 2 341

推荐阅读更多精彩内容