0

我有一个 8 段的分段控件。我可以更改整个控件的默认色调,但是我可以为控件中的每个段设置不同的颜色吗?我找到了一个在 5.1 中使用的教程,其中包含一个调用此方法的新类,

-(void)setTintColor:(UIColor*)color forTag:(NSInteger)aTag{}

但它在 iOS 6 中不起作用。有什么想法吗?

4

5 回答 5

2

此问题已在此处修复。由于格式问题,我无法粘贴源代码。 示例代码在这里。

编辑:从链接和固定格式添加注释和代码。〜奥利

它是一个hacky修复。这将起作用。将您的代码放在 ViewDidAppear 中。那会成功的。

- (void)viewDidAppear:(BOOL)animated 
{
    [super viewDidAppear: animated];
    dispatch_async(dispatch_get_main_queue(), ^{
        for (int i = 0 ; i < [segmentControl.subviews count] ; i++)
        {
            if ([[segmentControl.subviews objectAtIndex: i] isSelected] )
            {
                [[segmentControl.subviews objectAtIndex: i] setTintColor: [UIColor blackColor]];
                break;
            }
        }
    }); 
}
于 2012-11-06T08:37:09.917 回答
1

您可以为每个段设置不同的段图像和颜色。对于颜色,您可以使用:

//get the subviews of the segmentedcontrol

NSArray *arri = [segmentedControl subviews];

//change the color of every subview(segment) you have

[[arri objectAtIndex:0] setTintColor:[UIColor redColor]];

[[arri objectAtIndex:1] setTintColor:[UIColor greenColor]];

希望能解决问题。

于 2012-10-08T06:03:21.363 回答
0

你是对的……iOS 6 不支持分段控制的子视图……

我有一个替代方案给你:

CGRect rect = CGRectMake(0, 0, 80, 44);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context,
                               [[UIColor redColor] CGColor]);
CGContextFillRect(context, rect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[segment setImage:img forSegmentAtIndex:0];

您需要将核心图形框架添加到项目中。

我们可以在索引处为段绘制图像...。但是如果您使用它,您将无法使用段标题添加文本。您还需要在上面使用的图像“img”上绘制文本。如果您有其他方法,请分享。

于 2012-10-08T20:27:08.373 回答
0

这是一个设置红色并与 iOS 6 兼容的简单解决方案。

for ( UIView *segmentView in [segmentedControl subviews] ) {
    if ( [segmentView respondsToSelector:@selector(setTintColor:)] ) {
        [segmentView performSelector:@selector(setTintColor:)
                          withObject:[UIColor redColor]];
    }
}
于 2013-10-18T10:00:34.700 回答
0

UiSegmentedControl 有一个属性 'segmentedControlStyle'(在 iOS7 中已弃用),它会影响 'tintColor' 的行为

可能的样式是:

UISegmentedControlStylePlain,   
UISegmentedControlStyleBordered,
UISegmentedControlStyleBar,     
UISegmentedControlStyleBezeled, 

但实际上在 iOS6 中“Bezeled”(已弃用)等于“Bar”

对于前两种样式,无法更改已应用“tintColor”,要对其进行自定义,您需要使用以下方法更改每个段的图像:

- (void)setImage:(UIImage *)image forSegmentAtIndex:(NSUInteger)segment;

这样你将获得一个完全自定义的分段控件

但如果默认值足以满足您的设计,您可以使用样式

UISegmentedControlStyleBar

并且“tintColor”属性将生效,您将获得一个彩色分段控件,该控件根据所选段应用色调以及让系统使用它进行拨号的所有其他好处。

于 2014-01-23T11:46:14.313 回答