iOS

来源:互联网 发布:虎牙直播for mac 编辑:程序博客网 时间:2024/05/29 18:17

做项目免不了使用SegmentControl控件,系统的产品看不上,看上的系统实现不了,那就自定义呗。
先介绍下这个控件实现的功能:滑动切换,点击切换,字体颜色渐变,标题选中和未选中时的逐渐形变。
Git Demo地址链接:传送门

效果图:
segment
具体使用:

  1. 创建对象SegmentView,设置代理,传入对应的标题数组,设置正常时字体颜色,选中时颜色,字体font 。你也可以将控件设置成Navgationbar的titleview。

    -(DYSegmentView *)dySegment{if (!_dySegment) {    _dySegment = [[DYSegmentView alloc]initWithFrame:CGRectMake(ScreenWidth/2-120, 25, 240, 44)];    _dySegment.delegate         = self;    _dySegment.backgroundColor  = [UIColor clearColor];    _dySegment.titleNormalColor = UIColorFromRGB(0xffffff, 0.5);    _dySegment.titleSelectColor = UIColorFromRGB(0xffffff, 0.9);    _dySegment.titleFont        = [UIFont systemFontOfSize:15];    _dySegment.titleArray       = @[@"在线",@"附近"];}return _dySegment;}self.navigationItem.titleView = self.dySegment;
  2. 主界面创建Scrollview,添加创建滑动视图:可以是重用的tableview,也可以是不同的view,也可以是视图控制器。demo中,我创建了两个不同的视图控制器

  3. 实现Scrollview的代理方法,将滑动偏移量传到控件里面做出相对应的操作:

    -(void)scrollViewDidScroll:(UIScrollView *)scrollView{[_dySegment dyDidScrollChangeTheTitleColorWithContentOfSet:scrollView.contentOffset.x];}
  4. 实现segment点击控件的代理方法DYSegmentDelegate:

    -(void)dySegment:(DYSegmentView *)segment didSelectIndex:(NSInteger)index{NSString *notiStr;if (index == 1) {    notiStr = @"1";}else{    notiStr = @"2";}self.scrollView.contentOffset = CGPointMake(ScreenWidth*(index-1), 0);[[NSNotificationCenter defaultCenter] postNotificationName:@"MainViewScrollDidScroll" object:notiStr];}
    • 滑动时候字大小和颜色渐变的原理是根据偏移量算出左边和右边的偏移比例,使用CGAffineTransform逐渐形变按钮。获取到文字正常和选中时候的颜色色差,计算偏移时设置的颜色,实现方法在这里:
    -(void)dyDidScrollChangeTheTitleColorWithContentOfSet:(CGFloat)width;leftBtn.transform   = CGAffineTransformMakeScale(leftScale*BTN_BASE_SCALE+1, leftScale*BTN_BASE_SCALE+1);rightBtn.transform  = CGAffineTransformMakeScale(rightScale*BTN_BASE_SCALE+1, rightScale*BTN_BASE_SCALE+1);//选中和未选中的色差CGFloat redDif      = selectRed - normalRed;CGFloat greenDif    = selectGreen - normalGreen;CGFloat blueDif     = selectBlue - normalBlue;CGFloat alphaDif    = selectAlpha - normalAlpha;leftBtn.titleLabel.textColor = [UIColor colorWithRed:leftScale * redDif + normalRed green:leftScale * greenDif + normalGreen blue:leftScale * blueDif + normalBlue alpha:leftScale * alphaDif+normalAlpha];rightBtn.titleLabel.textColor = [UIColor colorWithRed:rightScale * redDif + normalRed green:rightScale * greenDif + normalGreen blue:rightScale * blueDif + normalBlue alpha:rightScale * alphaDif+normalAlpha];

Git Demo地址链接:传送门,能帮上忙的给个Star,有问题的可以联系584379066,备注:DYSegmentView

0 0
原创粉丝点击