自定义UISegmentedControl [英] Custom UISegmentedControl

查看:95
本文介绍了自定义UISegmentedControl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何制作自定义 UISegmentedControl

我有2张图片,该段是活动的,而另一个段是非活动的。我可以覆盖风格或东西,所以我有一个 UISegmentedControl 与我自己的图像作为活动/非活动背景?

I have 2 images, 1 that should be displayed when the segment is active and the other if the segment is inactive. Can i override the style or something so i have a UISegmentedControl with my own images as active/inactive background?

推荐答案

我不得不添加这个额外的代码,除了有on和off位置的两种不同的状态:

I had to add this extra code, in addition to having 2 different states for the "on" and "off" positions:

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Set set segControl background to transparent
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
    CGContextFillRect(context, rect);
    UIImage *transparentImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [self.segControl setBackgroundImage:transparentImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

    [self.segControl setDividerImage:transparentImage forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
}

编辑:因为这是一个宣传,一个更清洁的解决方案是使用[ UIImage new]而不是创建透明图像,如下:

Because this is getting some publicity, a cleaner solution is to use [UIImage new] instead of creating transparent images, as such:

 [self.segControl setDividerImage:[UIImage new] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
 [self.segControl setBackgroundImage:[UIImage new] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

这篇关于自定义UISegmentedControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆