它很容易改变UISegmentedControl的颜色。我找到了各种解决方案,例如this,this site和最佳this solution。但没有一个是我想要的。
我尝试创建一个简单的东西,它很容易,这是我的代码:(我使用的是iOS 4.2,而不是5.0和xcode 4.0.2)
id segment[3];
UISegmentedControl *segmentedControl;
- (id)init
{
NSArray *itens = [NSArray arrayWithObjects: @"Option 1", @"Option 2", @"Option 3", nil];
segmentedControl = [[UISegmentedControl alloc] initWithItems:itens];
[segmentedControl setFrame:CGRectMake(0, 0, 500, 30)];
[segmentedControl setSegmentedControlStyle:UISegmentedControlStyleBar];
[segmentedControl addTarget:self
action:@selector(segmentedControl:)
forControlEvents:UIControlEventAllEvents];
switch (type) {
case type1: [segmentedControl setSelectedSegmentIndex:0]; break;
case type2: [segmentedControl setSelectedSegmentIndex:1]; break;
case type3: [segmentedControl setSelectedSegmentIndex:2]; break;
}
for (int i=0; i<3; i++) {
//The most important trick to work, have to retain the subviews
segment[i] = [[[segmentedControl subviews] objectAtIndex:i] retain];
}
[self changeColor];
[self addSubview:segmentedControl];
return self;
}
- (void)segmentedControl:(id)sender
{
//do some thing
[self changeColor];
}
- (void)changeColor{
for (int i=0; i<3; i++) {
[segment[i] setTintColor:[UIColor lightGrayColor]];
}
int select = segmentedControl.selectedSegmentIndex;
[segment[select] setTintColor:[UIColor blueColor]];
}
所以它创造了这个:
非常好,然后点击Option 2
哇,这是我想要的,所以点击Option 3
现在问题是Option 1
和Option 2
之间的这条愚蠢的蓝线(用红色标记)。如果我再次点击Option 1
,我会:
再次出现蓝线。这意味着旧点击片段的每个左侧(但不包括第一个片段)将具有此蓝线。如果我从右到左,它就不会发生。
我不知道如何解决这个问题。如何访问此行并更改颜色?或者我将不得不使用其他代码。也许他们会遇到同样的问题...
答案 0 :(得分:5)
我认为有更简单的解决方案。 只需清理指针..
for (int i=0; i<[self.segmentedControll.subviews count]; i++)
{
[[self.segmentedControll.subviews objectAtIndex:i] setTintColor:nil];
if (![[self.segmentedControll.subviews objectAtIndex:i]isSelected])
{
UIColor *tintcolor=[UIColor blackColor];
[[self.segmentedControll.subviews objectAtIndex:i] setTintColor:tintcolor];
}
else
{
UIColor *tintcolor=[UIColor blueColor];
[[self.segmentedControll.subviews objectAtIndex:i] setTintColor:tintcolor];
}
}
答案 1 :(得分:3)
If I go from right to left it not happens.
这是解决方案!我该怎么办?模拟这个。
BOOL inside = FALSE;
- (void)changeColor{
int old = segmentedControl.selectedSegmentIndex;
for (int i=0; i<3; i++) {
[segment[i] setTintColor:[UIColor lightGrayColor]];
}
/**/inside = TRUE;
/**/for (int i=3; i>0; i--) {
/**/ //When I do this, it call "segmentedControl:"
/**/ [segmentedControl setSelectedSegmentIndex:i];
/**/}
/**/int select = old;
[segment[select] setTintColor:[UIColor blueColor]];
[segmentedControl setSelectedSegmentIndex:select];
/**/inside = FALSE;
}
- (void)segmentedControl:(id)sender
{
/**/if (inside==TRUE) return; //Ignore this calls.
//do some thing
[self changeColor];
}