定制自己的UISegmentedControl

UISegmentedControl

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

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

屏幕快照 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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • { 11、核心动画 需要签协议,但是系统帮签好 一、CABasicAnimation 1、创建基础动画对象 CAB...
    CYC666阅读 1,589评论 2 4
  • 代码创建UIWindow对象 Xcode7之后使用代码创建UIWindow对象: //创建UIWindow对象 s...
    云之君兮鹏阅读 1,360评论 0 2
  • 小城往南二百里,有名山。乃五岳之首,泰山也! 迄今为止,我已经六次登过泰山。 第一次登泰山,是在1997年的7月,...
    云清燕阅读 854评论 62 40
  • 今天听到一期关于6位院士坚持二十多年给武汉大学测绘专业学生上基础课的电台,真的是最奢华的基础课了。听的我真的好...
    白三娘阅读 226评论 0 0
  • JavaScript事件委托 原理:利用事件的冒泡原理,当你点击ul>li时,会从最深的节点开始向外传播li>ul...
    07120665a058阅读 249评论 0 1