定制自己的UISegmentedControl

UISegmentedControl

UISegmentedControl类似于UIButton,它可以提供多个选择操作,响应事件,但具有很大的局限性.

UISegmentedControl具有默认外观,字体颜色,和选中状态.
但有时候可能跟我们项目中的设计风格不统一.这就需要我们自定义外观.

定制自己的UISegmentedControl_第1张图片
屏幕快照 2017-09-15 下午1.54.50.png
#define RGB(r, g, b)                        RGBA(r, g, b, 1.0f)

1.首先去掉系统自带的默认效果

  UISegmentedControl *_segment = [[UISegmentedControl alloc] initWithItems:@[@"作品",@"喜欢"]];
  //系统用来设置UISegmentedControl的边框,分隔线,文字,点击后的颜色,将其更改为白色或者其他跟背景颜色相同的颜色.
  [_segment setTintColor:[UIColor whiteColor]];

2.设置选中和未选中的背景颜色

  [_segment setBackgroundImage:[UIImage getImageWithColor:RGB(243, 243, 243) size:CGSizeMake(20, 20)] forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
  [_segment setBackgroundImage:[UIImage getImageWithColor:[UIColor whiteColor] size:CGSizeMake(20, 20)] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

其中 (UIImage*)getImageWithColor:(UIColor*)color size:(CGSize)size 方法是在我在UIImage分类中定义的获取纯色背景图片.

+(UIImage*)getImageWithColor:(UIColor*)color size:(CGSize)size
{
    CGRect r= CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContext(r.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, r);
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}

3.设置字体颜色

//未选中状态
 [_segment setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]} forState:UIControlStateNormal];
  //设置选中状态      
 [_segment setTitleTextAttributes:@{NSForegroundColorAttributeName: RGB(80, 140, 238)} forState:UIControlStateSelected];

最后得出自己想要的UI外观,


屏幕快照 2017-09-15 下午1.50.58.png

另外大家可以根据需求,切圆角 和 加边框都是可以的.
有这样需求的可以试试...

你可能感兴趣的:(定制自己的UISegmentedControl)